How do I make an eventhandler run asynchronously?

2020-01-30 03:12发布

I am writing a Visual C# program that executes a continuous loop of operations on a secondary thread. Occasionally when that thread finishes a task I want it to trigger an eventhandler. My program does that but the when the event handler is triggered, the secondary thread waits until the event handler is finished before continuing the thread. How do I make it continue? Here is the way I currently have it structured...

class TestClass 
{
  private Thread SecondaryThread;
  public event EventHandler OperationFinished;

  public void StartMethod()
  {
    ...
    SecondaryThread.Start();      //start the secondary thread
  }

  private void SecondaryThreadMethod()
  {
    ...
    OperationFinished(null, new EventArgs());
    ...  //This is where the program waits for whatever operations take
         //place when OperationFinished is triggered.
  }

}

This code is part of an API for one of my devices. When the OperationFinished event is triggered I want the client application to be able to do whatever it needs to (i.e. update the GUI accordingly) without haulting the API operation.

Also, if I do not want to pass any parameters to the event handler is my syntax correct by using OperationFinished(null, new EventArgs()) ?

7条回答
再贱就再见
2楼-- · 2020-01-30 04:08

I prefer to define a method that I pass to the child thread as a delegate which updates the UI. First define a delegate:

public delegate void ChildCallBackDelegate();

In the child thread define a delegate member:

public ChildCallbackDelegate ChildCallback {get; set;}

In the calling class define the method that updates the UI. You'll need to wrap it in the target control's dispatcher since its being called from a separate thread. Note the BeginInvoke. In this context EndInvoke isn't required:

private void ChildThreadUpdater()
{
  yourControl.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background
    , new System.Threading.ThreadStart(delegate
      {
        // update your control here
      }
    ));
}

Before you launch your child thread, set its ChildCallBack property:

theChild.ChildCallBack = new ChildCallbackDelegate(ChildThreadUpdater);

Then when the child thread wants to update the parent:

ChildCallBack();
查看更多
登录 后发表回答