Can someone explain me why SqlDataAdapter.Fill fails in multithreading? I've prepared an example in LinqPad:
var connectionString = "Data Source=<server>;Initial Catalog=<DB>;Integrated Security=True";
var connection = new SqlConnection(connectionString);
connection.Open();
var lck = new object();
var tasks = new List<Task>();
for(var i=0; i<64; i++)
tasks.Add(Task.Factory.StartNew(() =>
{
using(var command = new SqlCommand(string.Format("select {0}", i), connection))
using(var ds = new DataSet())
using(var da = new SqlDataAdapter(command))
{
//lock(lck)
{
da.Fill(ds);
}
}
Console.Write("Ok ");
}));
Task.WaitAll(tasks.ToArray());
It gives me different errors all the time. And sometimes just hangs.
But if you uncomment the commented lock statement - everything will work fine.