Knowing UI Thread

  • Thread starter Tommaso Caldarola
  • Start date
M

Marc Gravell

Test InvokeRequired on an UI element (usually the Form instance); if it
returns true, then either .Invoke or .BeginInvoke against that UI element

private SomeHandler(object sender, EventArgs args) {
if(this.InvokeRequired) { // wrong thread
this.BeginInvoke(new EventHandler(SomeHandler), sender, args);
} else { // correct thread
// do something interesting
}
}

Marc
 
B

Brian Gideon

To determine whether the calling thread is a UI thread use
Application.MessageLoop, but I suspect that's not really what you're
after. If you're wanting to know if the calling thread can access a
particular control then use Control.InvokeRequired.

Brian
 
T

Tommaso Caldarola

Brian said:
To determine whether the calling thread is a UI thread use
Application.MessageLoop, but I suspect that's not really what you're
after. If you're wanting to know if the calling thread can access a
particular control then use Control.InvokeRequired.

My question is:

I write some data using Remoting.CallContext.SetData() in a BackgroundWorker
thread. So I need to retrieve the UI thread because afterwards I have to read
the data from UI thread.




Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
 
B

Brian Gideon

The BackgroundWorker.RunWorkerCompleted event will run on the UI
thread. Is that sufficient?
 
I

Ignacio Machin \( .NET/ C# MVP \)

HI,

I'm not sure if you can point out the UI from a list of threads.
What you can do is test if the current thread is the UI, by using
Control.InvokeRequired
 
T

Tommaso Caldarola

Brian said:
The BackgroundWorker.RunWorkerCompleted event will run on the UI
thread. Is that sufficient?

No because I write data in DoWork event.
 
M

Mehdi

No because I write data in DoWork event.

Then, in your DoWork method, use the Control.Invoke or Control.BeginInvoke
method of any of your UI controls to marshall the call to the UI thread.
The only thing to take care about is that these methods will work properly
only if the control on which they are called has already created his
Handle, that is if it has already been shown on the screen or if you have
manually forced the creation of its Handle.

Alternatively, you can call BackgroundWorker.ReportProgress from your
DoWork method to report progress to your UI thread. This method takes an
object as a parameter which will be given to the UI thread in the
ProgressChanged event allowing the UI thread to access whatever data it
needs.
 

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