Search code examples
c#wpfmultithreadingeventsaction

event Action Invoke from different thread in C#


public class A
{
    private B NotifyObj = new B();
    
    public A()
    {
        NotifyObj.NotifyEvent += Notified;
    }
     private async void Notified()
     {
         
     }
    
}

Class B
{
   public event Action NotifyEvent;

   public CallEvent()
   {
       NotifyEvent?.Invoke();
   }
}

In the above code(using C# WPF) class A is running in main thread and Class B is running in separate thread. What would happen if main thread is busy and other thread call CallEvent(). Is it going to get queue in the message queue or it will stop current execution and execute this then continue the previous execution. Basically does NotifyEvent?.Invoke() work like Postmessage/SendMessage in C++


Solution

  • If the method is called from a separate thread, it will be executed on the separate thread.

    If your need is to force the main thread (if not busy) to run some code, for example for handling the UI, you can check Dispatcher.Invoke method.