5

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.

3
  • 1
    It would help to be more specific about your purposes. Commented Jul 11, 2011 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 Commented Jul 11, 2011 at 13:26
  • please next time update your question instead of writing it in the comment. Commented Jul 12, 2011 at 10:31

1 Answer 1

18

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

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 What version of .Net are you using?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.