Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking method in a particular thread while processing in another thread

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?

like image 922
Ryszard Dżegan Avatar asked Dec 28 '25 14:12

Ryszard Dżegan


1 Answers

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);
like image 78
Ryszard Dżegan Avatar answered Dec 31 '25 04:12

Ryszard Dżegan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!