helloworld
helloworld

Reputation: 924

In threading program when do you use Invoke?

Example code:

private  void button1_Click(object sender, EventArgs e)
{
    Thread r= new Thread(new ThreadStart(DoWork));
    r.Start();
}

private void DoWork()
{
    MessageBox.Show("test");
    Thread.Sleep(2000);
} 

When would a developer replace the MessageBox code with:

this.Invoke(new Action(() => { MessageBox.Show(this, "test"); }));

Upvotes: 1

Views: 85

Answers (2)

Blindy
Blindy

Reputation: 67457

You use Invoke when you need to run code on the GUI thread. No more no less.

As to your last question, the only reason I can think of to do that is when you want to block your GUI thread until the user clicks the message box. There's no need for it.

Upvotes: 3

RagtimeWilly
RagtimeWilly

Reputation: 5445

You would use this.Invoke when you need the action to be executed on the UI thread.

For instance, if you were updating a UI element this would need to be executed on the Main UI thread.

Otherwise you would get an exception along the lines of:

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.

In your example, there's obviously no need to use Invoke

Upvotes: 4

Related Questions