Invoke in Windows Forms

前端 未结 1 458
野性不改
野性不改 2020-11-28 14:58

Does anyone have a link to a learning resource for using Invoke?

I\'m trying to learn but all the examples I have seen I have been unable to adapt for my purposes.<

相关标签:
1条回答
  • 2020-11-28 15:27

    Did you try MSDN Control.Invoke

    I just wrote a little WinForm application to demonstrate Control.Invoke. When the form is created, Start some work on background thread. After that work is done, Update the status in a label.

    public Form1()
    {
        InitializeComponent();
        //Do some work on a new thread
        Thread backgroundThread = new Thread(BackgroundWork);
        backgroundThread.Start();
    }        
    
    private void BackgroundWork()
    {
        int counter = 0;
        while (counter < 5)
        {
            counter++;
            Thread.Sleep(50);
        }
    
        DoWorkOnUI();
    }
    
    private void DoWorkOnUI()
    {
        MethodInvoker methodInvokerDelegate = delegate() 
                    { label1.Text = "Updated From UI"; };
    
        //This will be true if Current thread is not UI thread.
        if (this.InvokeRequired)
            this.Invoke(methodInvokerDelegate);
        else
            methodInvokerDelegate();
    }
    
    0 讨论(0)
提交回复
热议问题