简体   繁体   中英

System.Timers.Timer need to get back to 'Main' thread

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM