如何在同步代码.NET 4.5中等待所有并发任务完成?

时间:2015-06-13 03:32:37

标签: c# multithreading async-await

我有以下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

}

然后在我的应用程序的一个单独的类中我有这个方法(基于来自@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;
}

并像这样被调用

synchronous code...
synchronous code...

var result = DoOperationsConcurrentlyAsync(request.TenantId, request.Emails, request.Ssn);

synchronous code...
synchronous code...

所有这一切的目标是等待任务并行处理并希望减少我的全部时间......但是DoOperationsConcurrentlyAsync需要阻止,我该怎么做?然后作为奖励,如何使用async修饰符将返回值从各个任务传递回方法并退出方法?

1 个答案:

答案 0 :(得分:4)

我希望我能正确理解这一点。但是,您只是需要添加await关键字吗?

synchronous code...
synchronous code...

var result = await DoOperationsConcurrentlyAsync(request.TenantId, request.Emails, request.Ssn);

synchronous code...
synchronous code...

编辑:奖金问题:再次,我希望我能正确理解你......

但我会替换它:

await Task.WhenAll(tasks);

ValidationResponse[] result = new ValidationResponse[tasks.Length];

return result;

......简单地说:

return await Task.WhenAll(tasks);

这应该按你想要的方式工作。