I have created some async methods and have been adding records to a dataTable in those methods, and then bulk copying the dataTable after the async methods are done. I've found now that dataTables are not thread-safe, and that is the source of my problem, as I was noticing one or two records not actually getting inserted. I have something like this:
private async void yea()
{
DataTable t = new DataTable();
//Fill the data table with its columns
IEnumerable<Task<string>> results = items.Select(q => AsyncFunction(q.id, t));
Task<string[]> allTasks = Task.WhenAll(results);
string[] allResults = await results;
using (SqlConnection conn = new SqlConnection(_connString))
{
conn.Open();
using (SqlBulkCopy bc = new SqlBulkCopy(conn))
{
bc.BatchSize = 1000;
bc.DestinationTableName = tableName;
bc.WriteToServer(t);
}
}
}
public async Task<string> AsyncFunction(int id, DataTable t)
{
//await another Async function
DataRow dr = t.NewRow();
dr["ID"] = id;
//Many More columns
t.Rows.Add(dr);
return "success";
}
Like I said my problem is that the bulk copy often misses a few records. How can I bulk copy all of the records without losing them to non-thread safe calls?