Event by task Result

Possible duplicate:
How to create a task (TPL) using STA thread?

I am using the following code:

var task = Task.Factory.StartNew<List<NewTwitterStatus>>( () => GetTweets(securityKeys), TaskCreationOptions.LongRunning); Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { var result = task.Result; // ERROR!!! The calling thread cannot access this object because a different thread owns it. RecentTweetList.ItemsSource = result; Visibility = result.Any() ? Visibility.Visible : Visibility.Hidden; })); 

And I get the error message:

 var result = task.Result; // ERROR!!! The calling thread cannot access this object because a different thread owns it. 

What do I need to do to solve this problem?

+4
source share
3 answers

The idea behind Tasks is that you can link them:

  var task = Task.Factory.StartNew<List<NewTwitterStatus>>( () => GetTweets(securityKeys), TaskCreationOptions.LongRunning ) .ContinueWith(tsk => EndTweets(tsk) ); void EndTweets(Task<List<string>> tsk) { var strings = tsk.Result; // now you have your result, Dispatchar Invoke it to the Main thread } 
+12
source

You need to move the Dispatcher call to the continuation of the task, which will look something like this:

 var task = Task.Factory .StartNew<List<NewTwitterStatus>>(() => GetTweets(securityKeys), TaskCreationOptions.LongRunning) .ContinueWith<List<NewTwitterStatus>>(t => { Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { var result = t.Result; RecentTweetList.ItemsSource = result; Visibility = result.Any() ? Visibility.Visible : Visibility.Hidden; })); }, CancellationToken.None, TaskContinuationOptions.None); 
+1
source

It looks like you are starting a background task to start reading tweets, and then starting another task to read the result without any coordination between them.

I expect that your task will be another challenge to continue (see. Http://msdn.microsoft.com/en-us/library/dd537609.aspx ), and to continue, you may need to go back to the UI thread. ...

 var getTask = Task.Factory.StartNew(...); var analyseTask = Task.Factory.StartNew<...>( ()=> Dispatcher.Invoke(RecentTweetList.ItemsSource = getTask.Result)); 
+1
source

Source: https://habr.com/ru/post/1442773/


All Articles