Is SqlConnection thread-safe when methods are accessed in parallel by different threads?

127 Views Asked by At

I would like to know is a SqlConnection object created every time when the method is accessed by multiple threads and also would like to know is this method and the SqlConnection class is thread safe.

public DataSet GetData( string deptId)
{
    using(SqlConnection con = new SqlConnection(connectionString))
    {
        using(SqlDataAdapter da = new SqlDataAdapter(
            "Select * FROM Employee where DeptId='"+deptId+"'",con))
        {
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
    }
}
1

There are 1 best solutions below

0
Theodor Zoulias On

The SqlConnection is not thread-safe, meaning that an instance of this class cannot be used by multiple threads concurrently without synchronization.

Nevertheless the GetData method is thread-safe, because each time it is called it creates a separate SqlConnection instance. This SqlConnection object is used only by the current thread, and is not shared by any other code. Also the GetData method has no side-effects. It doesn't alter the state of the contained type in any way. It's the kind of method that is usually declared static. So you are free to call the GetData method from as many threads as you like, concurrently, without using the lock statement or any other form of synchronization.

It should be noted that there is nothing special with the SqlConnection not being thread-safe. The vast majority of the built-in .NET classes are not thread-safe. Non-thread-safety is the default. The few .NET classes that are thread safe, like the collections in the System.Collections.Concurrent namespace, are explicitly documented to be so. If you are looking at the documentation of a class and you are not finding anything related to thread-safety, you should assume that the class is not thread-safe.