循环异步调用WCF服务 [英] Calling WCF service asyncronously in a loop
问题描述
在我的WPF客户端中,我有一个循环,该循环调用WCF服务以更新一些记录.循环完成后,我会显示一条消息,更新完成".
In my WPF client, I have a loop that calls a WCF service to update some records. When the loop is done, I display a message, "Update complete".
我现在将WCF呼叫更改为异步呼叫.
I'm changing my WCF calls to async calls now.
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");
在每次操作的比赛中我都不需要做任何事情.我只需要在最后一个 末尾显示一条消息即可.
I don't need to do anything in the competed event of each operation. I need to just display a message at the end of the last one.
有什么想法吗?
我可能会将其移植到Silverlight,所以这就是为什么我需要异步调用该服务的原因.我认为我不能使用后台工作者.
I may be porting this to Silverlight, so that's why I need to call the service asyncronously. I don't think I can use the background worker.
推荐答案
我将在WPF窗口中添加一个线程安全字段,以跟踪用户排队的客户端更新数量:
I would add a thread-safe field to your WPF window to track the number of client updates the user has queued:
private int recordsQueued = 0;
在分派单个异步操作之前,请将recordsQueueed设置为someCollection.Count.
Before dispatching the individual async operations, set recordsQueued to someCollection.Count.
recordsQueued = someCollection.Count;
最后,在client_UpdateRecordsCompleted中,递减记录已排队;如果为零,则显示更新完成"消息:
Finally, in client_UpdateRecordsCompleted, decrement recordsQueued; if it is zero, display the "Update Complete" message:
private void client_UpdateRecordsCompleted(AsyncCompletedEventArgs args) {
if (Interlocked.Decrement(ref recordsQueued) == 0)
MessageBox.Show("Update complete.");
}
这篇关于循环异步调用WCF服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!