I have a list of object to process asynchronously
publiv void Processing(Task<MyObjects> myObjects)
{
var tasks = new List<Task>();
foreach(var myObject in myObjects.Result)
{
Task task = Task.Run(() => MyAsyncMethod(myObject));
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
}
void MyAsyncMethod(MyObject myObject)
{
// In some case I have to call the stored procedure
int result = MyStoredProcedure();
}
In MyAsyncMethod
, in some case (more or less often), I have to call a storee procedure (SQL Server). In this method:
public int MyStoredProcedure()
{
var connection = new SqlConnection("myConnectionString");
connection.Open();
using(connection)
{
var parameters = new DynamicParameters();
//some parameters here
connection.Execute("the stored procedure name", parameters, null, null, CommandType.StoredProcedure);
return valueValueFromStoreProc;
}
}
The code works when I have 1 or 2 items but I have much more to process.
I get this error when I open the connection
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
when I open the connection
Is it a problem of concurrency? A limitation of number of connections? Should I may be lock the section part in MyAsyncMethod
where I call the stored procedure? I tried a TransactionScope
around using in MyStoredProcedure
but I have the same problem.
Do you have an idea ?
Thanks