我想使用 .NET 中的任务框架来安排某些内容在不同的线程上运行,然后在完成后继续执行更新 UI 线程上的 UI 的操作。 (我还没有玩过它太多,所以它对我来说不是很熟悉。)
这是代码:
Task<List<NewsItem>> fetchTask = new Task<List<NewsItem>>(() =>
{
List<NewsItem> items = Rss.FetchNewsItems(feed);
return items;
}).ContinueWith(x => UpdateNewsItems(x.Result),CancellationToken.None,TaskContinuationOptions.None,scheduler);
private void UpdateNewsItems(List<NewsItem> items)
{
...
}
Cannot 隐式地将类型 'System.Threading.Tasks.Task' 转换为 'System.Threading.Tasks.Task>'。存在显式转换
我认为如果我使用 List 的通用签名关于 Task.Result 将返回该类型的任务,以便我可以将其传递给我的方法......
我在这里做错了什么?
I would like to use the Task framework in .NET to schedule something to run on a different thread then when it's done continue with an operation to update the UI on the UI thread. (I haven't played with it much yet, so it's not very familiar to me.)
Here is the code:
Task<List<NewsItem>> fetchTask = new Task<List<NewsItem>>(() =>
{
List<NewsItem> items = Rss.FetchNewsItems(feed);
return items;
}).ContinueWith(x => UpdateNewsItems(x.Result),CancellationToken.None,TaskContinuationOptions.None,scheduler);
private void UpdateNewsItems(List<NewsItem> items)
{
...
}
Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'System.Threading.Tasks.Task<System.Collections.Generic.List<Spark.Models.NewsItem>>'. An explicit conversion exists
I thought that if I use the generic signature of List<NewsItem> on the task that the Task.Result would return that type so I could pass it to my method...
What am I doing wrong here?
发布评论
评论(1)
问题是,由于您的 lambda 是一个
Action
,ContinueWith 返回一个Task
,并且您将其分配给fetchTask
,即类型为Task
。请注意,您将>
ContinueWith
调用的结果分配给变量,而不是new Task<>
调用的结果。如果您执行以下操作:
您会注意到存在问题,因为您的 lambda 返回 void,但任务期望返回
List
。因此,您可能想要从 UpdateNewsItems 返回该任务,或者创建任务并稍后添加延续。The issue is that since your lambda is an
Action<Task>
, ContinueWith returns aTask
, and you are assigning that tofetchTask
, which is of typeTask<List<NewsItem>>
. Note that you are assigning the result of theContinueWith
call to the variable, not the result of thenew Task<>
call.If you do something like this:
you will notice that there's a problem becuase your lambda returns void, but the task expects a return of
List<NewsItem>
. So you probably want to either return that from your UpdateNewsItems, or create the task and add the continuation later.