Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke in Windows Forms

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.

like image 450
Luke Peterson Avatar asked Dec 12 '22 11:12

Luke Peterson


1 Answers

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();
}
like image 106
iraSenthil Avatar answered Dec 28 '22 06:12

iraSenthil