tags:

views:

35

answers:

1

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  A: 

The issue is that since your lambda is an Action<Task>, ContinueWith returns a Task, and you are assigning that to fetchTask, which is of type Task<List<NewsItem>>. Note that you are assigning the result of the ContinueWith call to the variable, not the result of the new Task<> call.

If you do something like this:

Task<List<NewsItem>> fetchTask = new Task<List<NewsItem>>(() =>
        {
            List<NewsItem> items = Rss.FetchNewsItems(feed);
            return items;
        }).ContinueWith<List<NewsItem>>(x =>                  UpdateNewsItems(x.Result),CancellationToken.None,TaskContinuationOptions.None,scheduler);

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.

Philip Rieck