Reputation: 345
I have to call three different async methods from a WCF service. I have the following method that includes all three calls:
private async Task CreateMultipleTasksAsync()
{
CrimcaseServiceClient client = new CrimcaseServiceClient(
new BasicHttpBinding(),
new EndpointAddress("http://192.168.1.100/FooService/FooService.svc")
);
client.GetEventCompleted += OnGotEventResult;
client.GetEventAsync(eventInfo);
client.GetLocationsCompleted += OnGotLocationsResult;
client.GetLocationsAsync();
client.GetTypesCompleted += OnGotTypesResult;
client.GetTypesAsync();
}
After all three calls have been completed, I need to populate some values. But, I seem to be running into problems with how I can wait for all three to finish up first.
I've tried doing this, using this call, but it is still not waiting for all of the calls to complete before going on to the next bit of code:
private void GrabData()
{
var task = Task.Run(async () => { await CreateMultipleTasksAsync(); });
task.Wait();
}
Any suggestions would be greatly appreciated, as I'm lost at what to do at this point.
Thanks everyone.
Upvotes: 3
Views: 3977
Reputation: 456497
from a WCF service
I recommend that you rebuild your WCF client proxy, with asynchronous calls enabled. Currently, it is using an older pattern, but if you regenerate it with a modern Visual Studio version, it should result in a newer pattern that works better with async
/await
.
Then you can actually use await
with your WCF calls directly:
private async Task CreateMultipleTasksAsync()
{
CrimcaseServiceClient client = new CrimcaseServiceClient(
new BasicHttpBinding(),
new EndpointAddress("http://192.168.1.100/FooService/FooService.svc")
);
// Start the three asynchronous calls.
var getEventTask = client.GetEventAsync(eventInfo);
var getLocationsTask = client.GetLocationsAsync();
var getTypesTask = client.GetTypesAsync();
// Asynchronously wait (await) for them all to complete.
await Task.WhenAll(getEventTask, getLocationsTask, getTypesTask);
// Retrieve the results of the calls.
var event = await getEventTask;
var locations = await getLocationsTask;
var types = await getTypesTask;
// TODO: place OnGotEventResult / OnGotLocationsResult / OnGotTypesResult logic here
}
When you call it, you should do so just with an await
, not using Task.Run
or Task.Wait
:
await CreateMultipleTasksAsync();
// At this point, the results have been retrieved and processed.
Upvotes: 8