C# Events between threads executed in their own thread (How to)?

后端 未结 4 1079
孤街浪徒
孤街浪徒 2020-12-30 02:27

I\'d like to have two Threads. Let\'s call them :

  • Thread A
  • Thread B

Thread A fires an event and thread B listen to this event. When th

4条回答
  •  天命终不由人
    2020-12-30 03:16

    If you're using Windows Forms or WPF, and do not have a Control reference handy from your event handlers, you could also capture the reference of System.Threading.SynchronizationContext.Current in something running on the UI thread, and expose that reference to your event handlers.

    Then, when you need to have something run on the UI thread, invoke Post() or Send() on the captured SynchronizationContext reference from your event handler, depending on whether you want it to be run asynchronously or synchronously.

    Basically this is just sugar around capturing a Control reference and calling Invoke() on it, but can make your code simpler.

提交回复
热议问题