How do I make an eventhandler run asynchronously?

前端 未结 7 673
迷失自我
迷失自我 2020-12-04 11:15

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 e

7条回答
  •  执念已碎
    2020-12-04 11:51

    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();
    

提交回复
热议问题