1

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
TheBoubou
  • 19,487
  • 54
  • 148
  • 236
  • I suspect the proper place to process these items in parallel is in the stored procedure. – Mitch Wheat Jan 24 '21 at 09:28
  • The storeproc is 'just' to get a technical Id. There is a table with where all the techincal Id are stored (tables are not identity) and I have to live with. The storpoc get the value and increment of one and return the result. – TheBoubou Jan 24 '21 at 09:34
  • 1
    sounds like a horrible design! :) – Mitch Wheat Jan 24 '21 at 09:35
  • @MitchWheat no really !? :) Just a big sh#t but I have to live with – TheBoubou Jan 24 '21 at 09:38
  • What is the exact error you get? – Klaus Gütter Jan 24 '21 at 10:06
  • No, you should be able to open the connection, unless your SQL Server is configured for single-user mode. You may have waits and deadlocks after successfully opening multiple connections and trying to use them, but you should be able to open them to begin with. You might want to elaborate what exception you are getting. – GSerg Jan 24 '21 at 10:33
  • Does this answer your question? [C# Data Connections Best Practice?](https://stackoverflow.com/questions/17552829/c-sharp-data-connections-best-practice) – Charlieface Jan 24 '21 at 13:10

0 Answers0