Reputation: 3407
I'm trying to write to Azure Table Storage asynchronously using BeginExecute
but have been getting inconsistent results. When I change BeginExecute
to Execute
, then everything gets written properly, but I'm guessing I have something wrong in my threads that they are either cancelling each other or something depending on how fast the main thread sends the messages. Here's what I'm doing now:
TableOperation op = TableOperation.Insert(entity);
_table.BeginExecute(op, new AsyncCallback(onTableExecuteComplete), entity);
private void onTableExecuteComplete(IAsyncResult result)
{
TableResult tr = _table.EndExecute(result);
if ((tr.HttpStatusCode < 200) || (tr.HttpStatusCode > 202))
{
Console.WriteLine("Error writing to table.");
}
}
I'm testing it with a few entries, and I'll get one or two entries in the table, but not all of them. Any ideas on how to catch errors and make sure that all the entries are written properly?
Update: I found that when I put Thread.Sleep(5000);
at the end of my main thread, everything finishes writing. Is there a way to pause the main thread before it ends to ensure all other threads have finished so they don't get cancelled before they're done?
Upvotes: 2
Views: 1138
Reputation: 56769
Likely what is happening is that your main thread ends, and destroys all active child threads. When you are doing asynchronous programming, your main thread either needs to be running long enough to wait for completion (such as a service), or it needs to wait for asynchronous tasks to finish:
var result = _table.BeginExecute(op,
new AsyncCallback(onTableExecuteComplete), entity);
result.AsyncWaitHandle.WaitOne();
Source: http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx
This of course begs the question: if you are not needing to do anything else while you are waiting for the "asynchronous" task to complete, then you might as well do it synchronously to keep things simpler. The purpose of the asynchronous pattern is for threads that shouldn't be blocked while waiting for some other process to finish - at a cost of increased complexity.
Upvotes: 2