我必须从WCF服务调用三种不同的异步方法。我有以下方法,包括所有三个调用:
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();
}
完成所有三个调用后,我需要填充一些值。但是,我似乎遇到了如何等待所有三个人首先完成的问题。
我已尝试使用此调用执行此操作,但在继续执行下一段代码之前,它仍未等待所有调用完成:
private void GrabData()
{
var task = Task.Run(async () => { await CreateMultipleTasksAsync(); });
task.Wait();
}
任何建议都会非常感激,因为我在这一点上做了什么。
谢谢大家。
答案 0 :(得分:7)
来自WCF服务的
我建议您重新启动WCF客户端代理,并启用异步调用。目前,它正在使用an older pattern,但如果您使用现代Visual Studio版本重新生成它,则应该生成newer pattern,使其与async
/ await
更好地协作。< / p>
然后您可以直接使用await
与您的WCF调用:
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
}
当你打电话时,你应该只使用await
,而不是使用Task.Run
或Task.Wait
:
await CreateMultipleTasksAsync();
// At this point, the results have been retrieved and processed.