1

我刚刚升级到 .NET 4.5,我想利用异步方法功能。具体来说,我有一个外观,它进行 4 次不同的 api 调用并将响应聚合到一个响应对象中,该对象将从我的控制器返回。由于这 4 个调用不相关,它们可以异步完成并并行执行。我见过异步控制器的示例,但我希望并行调用发生在外观类本身中。这是我迄今为止所拥有的:

在 Facade.cs 中:

    public async Task<Dictionary<string, object>> AggregateServiceResponses(string authTicket)
    {
        var aggregateServiceResponse = new Dictionary<string, object>();
        var asyncManager = new AsyncManager();

        asyncManager.OutstandingOperations.Increment(4);

        await Task<Dictionary<string, object>>.Factory.StartNew(() =>
            {
                return _membershipServiceManager.GetMemberResponse(authTicket);
            }).ContinueWith(t =>
                {
                    asyncManager.Parameters["memberInfoResponse"] = t.Result;
                    asyncManager.OutstandingOperations.Decrement();
           });


        await Task<KeywordingResponseObject[]>.Factory.StartNew(() =>
            {
                return _keywordingServiceManager.GetKeywordResponse();
            }).ContinueWith(t =>
        {
            asyncManager.Parameters["Keywords"] = t.Result;
            asyncManager.OutstandingOperations.Decrement();
        });


        await Task<FamilyResponseObject[]>.Factory.StartNew(() =>
        {
            return _familyServiceManager.GetFamilyResponse();
        }).ContinueWith(t =>
        {
            asyncManager.Parameters["Family"] = t.Result;
            asyncManager.OutstandingOperations.Decrement();
        });


        await Task<IEnumerable<Friends>>.Factory.StartNew(() =>
        {
            return _friendsServiceManager.GetFriendsResponse();
        }).ContinueWith(t =>
        {
            asyncManager.Parameters["Friends"] = t.Result;
            asyncManager.OutstandingOperations.Decrement();
        });

       //After all service calls complete...build composite response...

        aggregateServiceResponse.Add("MemberInformation",asyncManager.Parameters["memberInfoResponse"]);
        aggregateServiceResponse.Add("Keywords", asyncManager.Parameters["Keywords"] );
        aggregateServiceResponse.Add("Family", asyncManager.Parameters["Family"]);
        aggregateServiceResponse.Add("Friends",asyncManager.Parameters["Friends"]);

        return aggregateServiceResponse;
    }
4

1 回答 1

4

您可以像这样同时执行此操作:

var memberTask = Task.Run(() => ...);
var kewordTask = Task.Run(() => ...);
var familyResponseTask = Task.Run(() => ...);
var friendsTask = Task.Run(() => ...);

await Task.WhenAll(memberTask, keywordTask, familyResponseTask, friendsTask);

但是,我必须指出,不建议在 ASP.NET 上进行并行(受 CPU 限制)处理,除非您正在编写只有少数并发用户请求的内部服务。

您也不再需要使用AsyncManager(或AsyncController)。

于 2013-06-06T15:22:21.653 回答