Automating the InvokeRequired code pattern

后端 未结 9 1367
醉话见心
醉话见心 2020-11-21 23:57

I have become painfully aware of just how often one needs to write the following code pattern in event-driven GUI code, where

private void DoGUISwitch() {
           


        
9条回答
  •  佛祖请我去吃肉
    2020-11-22 00:18

    I'd rather use a single instance of a method Delegate instead of creating a new instance every time. In my case i used to show progress and (info/error) messages from a Backroundworker copying and casting large data from a sql instance. Everywhile after about 70000 progress and message calls my form stopped working and showing new messages. This didn't occure when i started using a single global instance delegate.

    delegate void ShowMessageCallback(string message);
    
    private void Form1_Load(object sender, EventArgs e)
    {
        ShowMessageCallback showMessageDelegate = new ShowMessageCallback(ShowMessage);
    }
    
    private void ShowMessage(string message)
    {
        if (this.InvokeRequired)
            this.Invoke(showMessageDelegate, message);
        else
            labelMessage.Text = message;           
    }
    
    void Message_OnMessage(object sender, Utilities.Message.MessageEventArgs e)
    {
        ShowMessage(e.Message);
    }
    

提交回复
热议问题