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;
}
}
}
The
SqlConnectionis not thread-safe, meaning that an instance of this class cannot be used by multiple threads concurrently without synchronization.Nevertheless the
GetDatamethod is thread-safe, because each time it is called it creates a separateSqlConnectioninstance. ThisSqlConnectionobject is used only by the current thread, and is not shared by any other code. Also theGetDatamethod 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 declaredstatic. So you are free to call theGetDatamethod from as many threads as you like, concurrently, without using thelockstatement or any other form of synchronization.It should be noted that there is nothing special with the
SqlConnectionnot 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 theSystem.Collections.Concurrentnamespace, 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.