WCF service call asynchronously in a loop

In my WPF client, I have a loop that calls the WCF service to update some records. When the cycle is completed, I post the message "Update completed."

I am changing my WCF calls to asynchronous calls.

    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 do not need to do anything in the competition event of each operation. I just need to display a message at the end of the last.

Any ideas?

EDIT: I can port this to Silverlight, so I need to call the service asynchronously. I don’t think I can use a desktop background.

+1
source share
3 answers

I would add a streaming field to the WPF window to track the number of client updates delivered by the user:

private int recordsQueued = 0;

Queued someCollection.Count.

recordsQueued = someCollection.Count;

, client_UpdateRecordsCompleted, recordsQueued; , " ":

private void client_UpdateRecordsCompleted(AsyncCompletedEventArgs args) {
  if (Interlocked.Decrement(ref recordsQueued) == 0)
    MessageBox.Show("Update complete.");      
}
+2

, , . , . , - , .

+2

, :

ServiceClient client = new ServiceClient();
var count = someCollection.Count;
client.UpdateRecordsCompleted += (_,__) => {
    if (Interlocked.Decrement(ref count) == 0) {
        MessageBox.Show("Update complete.");   
    }
}

foreach (MyItem item in someCollection)
{
     client.UpdateRecordsAsync(item);
} 
+2

Source: https://habr.com/ru/post/1704536/


All Articles