I'm using multi-threaded database query to retrieve several data tables at once. I've used a list which is locked...and once all the callbacks are returned, I want to return the list. I want to know how to wait for all the callbacks to finish.
private Object TableLock = new Object();
private List<DataTable> tables_from_callback = new List<DataTable>();
private void ExecReaderHandleCallback(IAsyncResult result)
{
SqlCommand command = (SqlCommand)result.AsyncState;
SqlDataReader reader = command.EndExecuteReader(result);
DataTable dt = new DataTable();
dt.Load(reader);
lock (TableLock)
{
tables_from_callback.Add(dt);
}
}
public List<DataTable> BegExecReader(String query, int query)
{
conn = new SqlConnection(connectionString);
try
{
conn.Open();
WaitHandle[] waitHandles = new WaitHandle[query];
IAsyncResult[] results = new IAsyncResult[query];
SqlCommand[] cmds = new SqlCommand[query];
for (int i = 0; i < query; i++ )
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = queryTIMEOUT;
AsyncCallback callback = new AsyncCallback(ExecReaderHandleCallback);
cmd.BeginExecuteReader(callback, cmd);
cmds[i] = cmd;
}
/* ????
here I need to wait for the callbacks to finish
HOW?
??????? */
return tables_from_callback;
}
finally
{
conn.Close();
}
}
I've done something similar without using the callbacks where
IAsyncResult result = cmd.BeginExecuteReader();
results[i] = result;
waitHandles[i] = result.AsyncWaitHandle;
...
WaitHandle.WaitAll(waitHandles);
but now I MUST use the callback so I do not have the wait handles. Any help would be appreciated.