Reputation: 778
I have a Class(call it 'Foo') that has a System.Timers.Timer(call it 'myTimer').
Foo wraps unmanaged non thread-safe code.
On myTimer.Elapsed I need to use Methods in Foo.
Right now myTimer is trying use Foo's Methods on worker threads and this isn't working.
I need to get back to the thread that contains Foo' Methods.
How do I accomplish this? FYI, Foo's Methods are in a non-UI thread.
Upvotes: 2
Views: 1869
Reputation: 55720
If Foo is not a UI thread and you need to invoke code to execute on it from a different thread you will need to capture the synchronization context which executes Foo and then invoke your code from the timer on it.
Take a look at the SynchronizationContext class. You can either Post (asynchronously) or Send a delegate to be executed on a specific, previously captured, synchronization context.
You may also want/need to look into the ExecutionContext class. In particular: ExecutionContext.Capture and ExecutionContext.Run
Upvotes: 6