There is such a method

async Task<DataTable> TestAsync(string mySelectQuery, DB2Connection myConnection) { Task<DataTable> us = Task.Factory.StartNew(() => { using (DB2Command myCommand = new DB2Command(mySelectQuery, myConnection)) { using (DbDataReader myReader = myCommand.ExecuteReader()) { DataTable dt = new DataTable(); dt.Load(myReader); return dt; } } }); return await us; } 

I call this:

 IEnumerable<Task<DataTable>> tasks = from unds in new [] { "select * from test1", "select * from test2" } select TestAsync(unds, myConnection); DataTable[] uds = await Task.WhenAll(tasks); 

And an exception is thrown.

Failed to enable constraints. One or more rows contain values ​​violating non-null, unique, or foreign-key constraints

Someone can explain to me why in this case DataTable gives an error? is it local, and with asyncry, the method is copied and all its local variables too? But if you do like this, then there is no error!

 lock (ob) { DataTable dt = new DataTable(); dt.Load(myReader); return dt; } 
  • An asynchronous method that contains only return await is stupid. From your code, you can remove the words async and await without losing meaning. - Pavel Mayorov

1 answer 1

The DB2Connection class DB2Connection not designed to work in two threads at once. You need to create a separate connection for each request.

  • Yes, but this increases the execution time. And if you use one connection but load it into the DataTable in the lock construction, then for 2 seconds. faster. Or is there an option for better how to make asynchronous queries in the database? - Dmitriy
  • one
    @Dmitriy your lock construct makes loading data consistently. You can add the same effect if you make them sequentially instead of executing queries in parallel. - Pavel Mayorov
  • I need to make requests of the order to 10 tables each time and if it is done consistently, it will affect the application performance. It would be desirable to get out parallel requests. Is it possible Is there an example? - Dmitriy
  • one
    @Dmitriy yes, maybe - if you use different connections. - Pavel Mayorov