Run code on UI thread without control object present

前端 未结 5 1782
予麋鹿
予麋鹿 2020-12-08 16:57

I currently trying to write a component where some parts of it should run on the UI thread (explanation would be to long). So the easiest way would be to pass a control to i

5条回答
  •  生来不讨喜
    2020-12-08 17:25

    Put the UI manipulation in a method on the form to be manipulated and pass a delegate to the code that runs on the background thread, à la APM. You don't have to use params object p, you can strongly type it to suit your own purposes. This is just a simple generic sample.

    delegate UiSafeCall(delegate d, params object p);
    void SomeUiSafeCall(delegate d, params object p)
    {
      if (InvokeRequired) 
        BeginInvoke(d,p);        
      else
      {
        //do stuff to UI
      }
    }
    

    This approach is predicated on the fact that a delegate refers to a method on a particular instance; by making the implementation a method of the form, you bring the form into scope as this. The following is semantically identical.

    delegate UiSafeCall(delegate d, params object p);
    void SomeUiSafeCall(delegate d, params object p)
    {
      if (this.InvokeRequired) 
        this.BeginInvoke(d,p);        
      else
      {
        //do stuff to UI
      }
    }
    

提交回复
热议问题