Bea*_*ood 6 .net c# asynchronous task async-await
只是想知道异步时最好的方法.起初我的代码看起来像这样(示例简化了).
public NotificationSummary SendNotification()
{
var response = new NotificationSummary();
var first = FindSubscriptions(1);
...
var seventh = FindSubscriptions(7);
Task.WaitAll(first, ... , seventh);
response.First = first.Result;
...
response.Seventh = seventh.Result;
return response;
}
private Task<NotificationResult> FindSubscriptions(int day)
{
return Task.Run(() =>
{
var subscriptions = // call to database to get list of subscriptions
var tasks = subscriptions.Select(x => SendOutNotification(x))
var results = Task.WhenAll(tasks).Result.ToList();
return // map results to NotificationResult
}
}
private Task<IndividualResult> SendOutNotification(Subscription subscription)
{
return Task.Run(() =>
{
var response = new IndividualResult();
foreach(var user in subscription.Users)
{
try
{
// Send user info to EMAIL API
response.Worked.Add(user);
}
catch(Exception ex) { response.Failed.Add(user)}
}
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
但是这种方法违反了单一责任,当他们来试图弄清楚这些代码在做什么时,可能会让其他开发人员感到困惑.我试图找到一种方法将任务链接在一起,我遇到了ContinueWith.我做了一些研究(也看了看其他stackoverflow帖子),我对ContinueWith进行了混合评论.我真的希望我的SendNotification方法看起来像这样,但我不知道这对于异步和任务是否是一个好方法.
public NotificationSummary SendNotification()
{
var response = new NotificationSummary();
var firstTasks = new List<IndivdualResult>();
var first = FindSubscriptions(1).ContinueWith( x=>
x.Result.ForEach(r =>
firstTasks.Add(SendOutNotification(x).Result)));
response.First = // map first;
// do 2 - 7 tasks as well
return response;
}
private Task<List<Subscription>> FindSubscriptions() {} //returns subscriptions
private Task<IndividualResults> SendOutNotication() {} // same as above
Run Code Online (Sandbox Code Playgroud)
我想知道这些方法中的哪一种会被视为"正确的方法",如果有的话?
ContinueWith是await可用的代码味道.await基本上是附加延续的好方法.
我发现第一版代码没有结构问题.你可能应该:
Wait/Result呼叫await这应该清理混乱并解决效率问题.
如果您不需要并行性,您也可以使所有内容同步.