ScottG
ScottG

Reputation: 11121

Calling WCF service asyncronously in a loop

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".

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.

Any ideas?

EDIT: 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.

Upvotes: 1

Views: 2288

Answers (3)

Jeff Sternal
Jeff Sternal

Reputation: 48583

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;

Before dispatching the individual async operations, set recordsQueued to someCollection.Count.

recordsQueued = someCollection.Count;

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.");      
}

Upvotes: 2

MichaelGG
MichaelGG

Reputation: 10006

Perhaps like this:

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);
} 

Upvotes: 2

Darryl Braaten
Darryl Braaten

Reputation: 5231

If you don't want to overwhelm your server with requests another approach would be to use a background worker, do all your work in a normal loop with synchronous requests. A background worker already has methods for reporting progress and completion which are handy to report back to your main application on the correct thread. Assuming you want to do stuff with your GUI instead of just displaying complete dialog.

Upvotes: 2

Related Questions