How to pass an object reference to a task (TPL)?

I have a method that I want to execute in the background using Task. However, the method requires an object reference as a parameter. However, the object is created in the user interface thread, so I got "the calling thread cannot access this object because another thread belongs to it." an exception. How am I supposed to do this?

Task.Factory.StartNew(() => SerializeGraphicsLayer(graphicsLayer, fileUrl)) .ContinueWith((t) => UpdateSaveOperation(t), TaskScheduler.FromCurrentSynchronizationContext()); 

The SerializeGraphicsLayer () method is the one I want to use in the background, however I need to pass a link to the object created in the UI thread to this method ...

EDIT: The method (which works in backgound) may throw an exception, and the UpdateSaveOperation () method will make the necessary error message in the user interface.

I would like to have a good exception handling, and that is why I chose Task for this?

+4
source share
2 answers

A UI object is not a good candidate for use in a background thread. If possible, you can get the necessary values ​​and fix them in your work:

 string name = userName.Text; // access values on UI thread Task.Factory.StartNew(() => /* something using name, but not the UI control*/ ); 

However, if you need to update the values ​​to the user interface, you will need to return to the user interface thread. If all you do is update the user interface, you can also not use TPL (this is not very convenient).

+1
source

In WPF, you can use the Dispatcher class to perform heavy non-UI tasks that you can easily transfer to the background thread. For more information, see the following article: Understanding Dispatcher in WPF

When calling methods through Dispatcher, you can pass any object as a parameter and in the called method, you will have to return it back to the original type.

+1
source

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


All Articles