在我的 WPF 客户端中,我有一个循环调用 WCF 服务来更新一些记录。循环完成后,我会显示一条消息“更新完成”。
我现在将我的 WCF 调用更改为异步调用。
ServiceClient client = new ServiceClient();
client.UpdateRecordsCompleted +=new System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_UpdateRecordsCompleted);
foreach (MyItem item in someCollection)
{
client.UpdateRecordsAsync(item);
}
MessageBox.Show("Update complete");
我不需要在每个操作的竞争事件中做任何事情。我只需要在最后一条消息的末尾显示一条消息。
有任何想法吗?
编辑:我可能会将其移植到 Silverlight,这就是为什么我需要异步调用该服务的原因。我不认为我可以使用后台工作人员。
最佳答案
我会在您的 WPF 窗口中添加一个线程安全字段,以跟踪用户已排队的客户端更新数量:
private int recordsQueued = 0;
在调度各个异步操作之前,将 recordsQueued 设置为 someCollection.Count。
recordsQueued = someCollection.Count;
最后,在client_UpdateRecordsCompleted中,递减recordsQueued;如果为零,则显示“更新完成”消息:
private void client_UpdateRecordsCompleted(AsyncCompletedEventArgs args) {
if (Interlocked.Decrement(ref recordsQueued) == 0)
MessageBox.Show("Update complete.");
}
关于wcf - 在循环中异步调用 WCF 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/537786/