I want to select some data from tables at the same time. When I am trying to do this with parallel threads an exception occurs. Should I use different SqlConnection
objects for every SqlCommand
or is there any technique to share same SqlConnection
between several threads and execute several SqlCommand
at the same time without exception.
SqlConnection connection = new SqlConnection("...")
connection.Open();
List<Task> tasks = new List<Task>();
for (int i = 0; i < 10; i++)
{
tasks.Add(Task.Run(() =>
{
var command = connection.CreateCommand();
command.CommandText = "select top 1 * from Persons";
var data = command.ExecuteReader();
while (data.Read())
{
Console.WriteLine($"{data[0]} {data[1]} {data[2]}");
}
}));
}
await Task.WhenAll(tasks);
connection.Close();