4

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.

gsharp
  • 27,557
  • 22
  • 88
  • 134
Luke Peterson
  • 43
  • 1
  • 1
  • 3
  • 1
    It would help to be more specific about your purposes. – gsharp Jul 11 '11 at 13:22
  • Sorry, I'm writing a program which communicates with a device via a serial connection. Currently, the program tries to run a section of code until an input changes, however the section is on a GUI thread and so the program can't respond to changes. I've been told I therefore need to put the section of code on another thread and use Invoke to access it. Hope this helps, thanks – Luke Peterson Jul 11 '11 at 13:26
  • please next time update your question instead of writing it in the comment. – gsharp Jul 12 '11 at 10:31

1 Answers1

15

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();
}
iraSenthil
  • 11,307
  • 6
  • 39
  • 49
  • Thanks a lot, this is great, exactly what I was looking for! I have been trying to use Control.Invoke but didn't really understand what I was doing. One question though - I'm getting an error: "'delegate': identifier not found" Thanks! – Luke Peterson Jul 12 '11 at 08:43
  • @Luke What version of .Net are you using? – iraSenthil Jul 12 '11 at 13:04