我刚刚升级到 .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;
}