C# 使用BeginExecute写入Azure表存储
我试图使用C# 使用BeginExecute写入Azure表存储,c#,azure,asynchronous,azure-storage,C#,Azure,Asynchronous,Azure Storage,我试图使用BeginExecute异步写入Azure表存储,但结果不一致。当我将BeginExecute更改为Execute时,所有内容都会正确写入,但我猜我的线程中存在一些错误,它们要么相互取消,要么取决于主线程发送消息的速度。以下是我现在正在做的: TableOperation op = TableOperation.Insert(entity); _table.BeginExecute(op, new AsyncCallback(onTableExecuteComplete), entit
BeginExecute
异步写入Azure表存储,但结果不一致。当我将BeginExecute
更改为Execute
时,所有内容都会正确写入,但我猜我的线程中存在一些错误,它们要么相互取消,要么取决于主线程发送消息的速度。以下是我现在正在做的:
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.");
}
}
TableOperation op=TableOperation.Insert(实体);
_table.BeginExecute(op,新的AsyncCallback(onTableExecuteComplete),实体);
私有void onTableExecuteComplete(IAsyncResult结果)
{
TableResult tr=_table.EndExecute(结果);
如果((tr.HttpStatusCode<200)| |(tr.HttpStatusCode>202))
{
WriteLine(“写入表时出错”);
}
}
我用几个条目测试它,我会在表中得到一个或两个条目,但不是全部。关于如何捕捉错误并确保正确写入所有条目,您有什么想法吗
更新:我发现当我把
Thread.Sleep(5000)代码>在我的主线程结束时,所有内容都完成了编写。有没有办法在主线程结束之前暂停它,以确保所有其他线程都已完成,这样它们就不会在完成之前被取消?可能发生的情况是主线程结束,并销毁所有活动的子线程。在执行异步编程时,主线程需要运行足够长的时间以等待完成(如服务),或者需要等待异步任务完成:
var result = _table.BeginExecute(op,
new AsyncCallback(onTableExecuteComplete), entity);
result.AsyncWaitHandle.WaitOne();
资料来源:
这当然回避了一个问题:如果您在等待“异步”任务完成时不需要执行任何其他操作,那么您最好同步执行,以使事情更简单。异步模式的目的是为那些在等待其他进程完成时不应该被阻塞的线程提供支持,这会增加复杂性。我一直在寻找AsyncWaitHandle
,谢谢。现在,我只需跟踪挂起的操作,并使用WaitOne
确保它们在退出应用程序之前完成。