作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我昨天开始为我的一个小项目使用 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是我去获取我需要的信息的地方。查看代码示例
最佳答案
解决问题的两种方法:
拆分任务变量的声明:
Task<List<Object>> myTask = Task<List<Object>>.Factory.StartNew(() =>
{
//business logic creating an Object to return
//return Object created
});
Task taskContinuation = myTask.ContinueWith((antecedant) =>
{
//business logic : needs to use antecedant
}, TaskScheduler.FromCurrentSynchronizationContext());
这将允许您独立运行这两个任务,其中 continuation
是 Task
类型。
第二种也是更好的方法 IMO 是使用 async-await
:
public async Task CreateFooAsync()
{
List<object> objects = await Task.Run(() => /* Create object */);
// here you're on the UI thread, continue execution flow as normal.
}
请注意,async-await
的语义意味着第一个任务将异步等待对象的创建。
关于c# - 使用任务 : ContinueWith needs a return statement which my business logic doesn't require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29804392/
我是一名优秀的程序员,十分优秀!