[英]How to wait for all concurrent Tasks to complete in synchronous code .NET 4.5?
I have the following ServiceStack web service 我有以下ServiceStack Web服务
public class RetreadServices : Service
{
public IRepository Repository { get; set; }
//http://stackoverflow.com/questions/18902135/servicestack-no-server-side-async-support
public async Task<ValidationResponse> Get(RetreadSsnInfoAsync request)
{
return await Task.Factory.StartNew(() =>
{
Tenant.SetTenant(request.TenantId);
return new ValidationResponse { Result = Repository.CannotRetreadSsn(request.Ssn) };
});
}
public async Task<ValidationResponse> Get(RetreadEmailInfoAsync request)
{
return await Task.Factory.StartNew(() =>
{
Tenant.SetTenant(request.TenantId);
return new ValidationResponse { Result = Repository.CannotRetreadEmail(request.Emails) };
});
}
//more methods constructed in the same fashion
}
then in a separate class in my application I have this method (based off of code from @StephenCleary) 然后在我的应用程序的单独类中,我有此方法(基于@StephenCleary的代码)
private async Task<ValidationResponse[]> DoOperationsConcurrentlyAsync(string tenantId, string[] emails, string ssn)
{
Task<ValidationResponse>[] tasks =
{
ResolveService<RetreadServices>().Get(new RetreadEmailInfoAsync { TenantId = tenantId, Emails = emails }),
ResolveService<RetreadServices>().Get(new RetreadSsnInfoAsync { TenantId = tenantId, Ssn = ssn })
};
await Task.WhenAll(tasks);
ValidationResponse[] result = new ValidationResponse[tasks.Length];
return result;
}
and being invoked like this 并像这样被调用
synchronous code...
synchronous code...
var result = DoOperationsConcurrentlyAsync(request.TenantId, request.Emails, request.Ssn);
synchronous code...
synchronous code...
The goal of all of this is to wait while the tasks process in parallel and hopefully decrease my over-all time... but the DoOperationsConcurrentlyAsync needs to block, how do I do that? 所有这些的目标是等待任务并行执行,并希望减少我的整体时间...但是DoOperationsConcurrentlyAsync需要阻止,我该怎么做? Then as a bonus, how do I pass the return values back from the individual tasks up and out of the method with the async modifier? 然后,作为奖励,我如何使用async修饰符将返回值从各个任务传回方法之外?
I hope I'm understanding this correctly. 希望我能正确理解。 But don't you just need to add the await
keyword? 但是,您不只是需要添加await
关键字吗?
synchronous code...
synchronous code...
var result = await DoOperationsConcurrentlyAsync(request.TenantId, request.Emails, request.Ssn);
synchronous code...
synchronous code...
EDIT: Bonus question: Again, I hope I'm understanding you correctly... 编辑:奖金问题:再次,我希望我能正确理解你...
But I would replace this: 但是我将替换为:
await Task.WhenAll(tasks);
ValidationResponse[] result = new ValidationResponse[tasks.Length];
return result;
...with simply this: ...简单地说:
return await Task.WhenAll(tasks);
That should work the way you want it. 那应该按照您想要的方式工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.