I was under the impression that using Task’s ContinueWith method with a UI context allows performing operations on UI elements without causing a cross-thread exception. However, I am still getting an exception when running the following code:
var context = TaskScheduler.FromCurrentSynchronizationContext();
Task<SomeResultClass>.Factory.StartNew(SomeWorkMethod).ContinueWith((t) =>
{
myListControl.Add(t.Result); // <-- this causes an exception
}, context);
Any ideas?
There are two different causes of cross-thread exceptions.
The most common one is that you try to modify the state of a control from the non-UI thread. And this is not the issue you’re hitting.
The one you’re hitting is that controls must be created on the UI thread. Your task is creating the control on a different thread and when you try to add this control to controls created on the UI thread you get the exception.
You need to separate out the work from the control creation to make this work. Try returning a
Func<Control>rather than aControland invoke this on the UI thread before adding it. Keep most of the work on the task thread but form a nice tight closure by returning theFunc<>that just does the control creation.