我刚刚升级到.NET 4.5,我想利用异步方法功能。具体来说,我有一个外观,它可以进行4个不同的api调用,并将响应聚合到一个响应对象中,该对象将从我的控制器返回。由于这4个调用不相关,因此它们可以异步完成并并行执行。我已经看过异步控制器的例子,但我希望并行调用发生在facade类本身中。这就是我到目前为止所做的:
在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;
}
答案 0 :(得分: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
)。