Reputation: 25434
I'm starting a long running task like that:
task = Task.Factory.StartNew(LongRunningMethod, TaskCreationOptions.LongRunning);
In LongRunningMethod I'm calling third party methods which are raising events. That events contain data that I need to add to my data table:
dataTable.Rows.Add(e.Data);
The trouble is, that the dataTable can be associated with some view that requires calling Invoke method, but I don't want to add any references to interfaces, that implement Invoke like method.
I would like to do something like that:
originalThread.Invoke(() => dataTable.Rows.Add(e.Data));
What are the best options to achieve that goal?
Upvotes: 3
Views: 2229
Reputation: 25434
By aggregating helpful comments I can produce an answer.
According to Henk Holterman, there is no possibility to interrupt original thread, store its context, perform some action and then restore its previous context and run further.
There are specific solutions for target presentation layers like BackgroundWorker Class in WinForms and Dispatcher Class in WPF.
I believe that for my scenario the suggestion from sll works best. I can use SynchronizationContext Class and its Post Method. Below is an example:
originalSynchronizationContext = SynchronizationContext.Current;
task = Task.Factory.StartNew(LongRunningMethod, TaskCreationOptions.LongRunning);
In parallel LongRunningMethod:
originalSynchronizationContext.Post(state => dataTable.Rows.Add(e.Data), null);
Upvotes: 2