Question on InvokeRequired

G

Guest

Hello,

I'm still new to multithreading and I was just playing around with threads
and the UI and have a question.

I have this code in my form:

private void button3_Click(object sender, System.EventArgs e)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
}

private delegate void ThreadProcDelegate();
private void ThreadProc()
{
if(InvokeRequired)
{
Invoke(new ThreadProcDelegate(ThreadProc),null);
return;
}
this.Text = DateTime.Now.ToString("dd-MMM-yy");
}

Now, when the new thread starts, it correctly calls Invoke to run the method
because InvokeRequired returned true. After Invoke is called, InvokeRequired
is false.

My question is does InvokeRequired return true whenever you are in a non-gui
thread regardless if you are accessing any UI controls in the non-gui thread
or not?

Thanks,
-Flack
 
J

Jon Skeet [C# MVP]

Flack said:
I'm still new to multithreading and I was just playing around with threads
and the UI and have a question.

I have this code in my form:

private void button3_Click(object sender, System.EventArgs e)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
}

private delegate void ThreadProcDelegate();
private void ThreadProc()
{
if(InvokeRequired)
{
Invoke(new ThreadProcDelegate(ThreadProc),null);
return;
}
this.Text = DateTime.Now.ToString("dd-MMM-yy");
}

Now, when the new thread starts, it correctly calls Invoke to run the method
because InvokeRequired returned true. After Invoke is called, InvokeRequired
is false.

Yes - but of course it gets rid of any point in creating a new thead in
the first place.
My question is does InvokeRequired return true whenever you are in a non-gui
thread regardless if you are accessing any UI controls in the non-gui thread
or not?

Absolutely - it can't possible know whether you're about to access a UI
control. InvokeRequired is basically checking whether or not you're on
the creating thread for the control you call it on.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top