Besides the reasons and possible solutions, Enigmativity said allready, you can always do something like this:
var context = TaskScheduler.FromCurrentSynchronizationContext(); Task<SomeResultClass>.Factory.StartNew(SomeWorkMethod).ContinueWith((t) => { if (!myListControl.InvokeRequired) myListControl.Add(t.Result); // <-- this causes an exception else myListControl.Invoke((Action)(() => myListControl.Add(t.Result))); }, context);
(assumed to be WinForms)
if you want mor control refactor to add to the method and use InvokeRequired inside the method to call itself inside Invoke if necessary:
private void AddToListControl(MyItem item) { if (myListControl.InvokeRequired) { myListControl.Invoke((Action)(() => AddToListControl(item))); return; } myListControl.Add(item); }
What Enigmativity hints is something like this:
var result = Task<Action>.Factory.StartNew(SomeWorkMethod).ContinueWith((t) => { return () => myListControl.Add(t.Result); }); result.Result();
But IMHO is the same place that you got from the very beginning, because you need to call Result-Action in the right thread again.
source share