gpt4 book ai didi

c# - 使用任务 : ContinueWith needs a return statement which my business logic doesn't require

转载 作者:行者123 更新时间:2023-11-30 12:43:55 24 4
gpt4 key购买 nike

我昨天开始为我的一个小项目使用 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());

这将允许您独立运行这两个任务,其中 continuationTask 类型。

第二种也是更好的方法 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com