PC Review Forums Newsgroups Microsoft DotNet Microsoft Dot NET Framework Forms Question on InvokeRequired

Reply

Question on InvokeRequired

 
Thread Tools Rate Thread
Old 02-06-2005, 08:23 PM   #1
=?Utf-8?B?RmxhY2s=?=
Guest
 
Posts: n/a
Default Question on InvokeRequired


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
  Reply With Quote
Old 02-06-2005, 08:27 PM   #2
Jon Skeet [C# MVP]
Guest
 
Posts: n/a
Default Re: Question on InvokeRequired

Flack <Flack@discussions.microsoft.com> wrote:
> 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.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
  Reply With Quote
Reply



Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off