【发布时间】:2015-04-22 17:05:48
【问题描述】:
我昨天开始在我的一个小项目中使用 Tasks。在代码中设置好任务逻辑后,我意识到我不得不在 ContinueWith() 函数中使用 return 语句。
即使myTask 首先需要返回一个对象,有什么方法可以避免在 ContinueWith 中返回?
Task<List<Object>> myTask = Task<List<Object>>.Factory.StartNew(() =>
{
//business logic creating an Object to return
//return Object created
})
.ContinueWith<List<Object>>((antecedant) =>
{
//business logic : needs to use antecedant
return null; //can i get rid of this? I don't need to return an object in this section
}, TaskScheduler.FromCurrentSynchronizationContext());
让我们说 return null 语句让我很烦......
注意:针对 Yuval 的评论,我使用的是 .net framework 4.5
解决方案
根据 CoryNelson 的评论,我想出了这段代码。它完全符合我的需求。
Task<List<Object>> myTask = Task<List<Object>>.Factory.StartNew(() =>
{
//business logic creating an Object to return
//return Object created
});
Task myFollowingTask = myTask.ContinueWith((antecedant) =>
{
//business logic using antecedant
}, TaskScheduler.FromCurrentSynchronizationContext());
我不再需要 ContinueWith 中的 return 语句了。
Here 是我获取所需信息的地方。见代码示例
【问题讨论】:
-
有一个重载需要一个动作而不是一个函数。你应该能够摆脱你的回报并让它发挥作用。
-
@Cory Nelson 谢谢,我会查一下!您指的是 ContinueWith 重载,对吗?
-
那你为什么要
Task<List<object>>?为什么不用Task而不是你不需要返回类型。 -
因为我需要在 ContinueWith 中使用先行词。 antecedant 将是从
myTask创建和返回的- >。
-
您可以将它们分成两个单独的任务。顺便说一句,您使用的是哪个版本的 .NET 框架?
标签: c# .net task-parallel-library