[RESOLVED] Changing GUI from another thread
I have been working with C# for about 6 months now, and started working with threads last week. I created an application that has a couple of threads and one of these needs to change the gui. I can't seem to able to do this, so any help on the matter is greatly appreciated.
Re: Changing GUI from another thread
How many times does this have to be re-answered.... :rolleyes:
You can ONLY reference controls on the thread that created them. To perform a cross-thread GUI update, you must pass the information back to the UI thread, and let that thread do the work.
The simplest way is with the Invoke method that is supported by every class derived from Control.
See the threads here (A simple search on CG....)
Re: Changing GUI from another thread
I have tried that but it still doesn't work.
Re: Changing GUI from another thread
Post a small sample and specify the issues you are having.
Re: Changing GUI from another thread
Code:
BackgroundClass bgC = new BackgroundClass(this.Level);
new Thread(new ThreadStart(bgC.setLevel)).Start();
Thread - Started by above:
Code:
namespace ThreadedApp
{
class BackgroundClass
{
MainForm mf = new MainForm();
float battLevel;
public BackgroundClass(float Level)
{
this.battLevel = Level;
}
public void setLevel()
{
mf.setBatteyLvl(this.battLevel);
}
}
}
GUI:
Code:
namespace ThreadedApp
{
class MainForm
{
delegate void setBatteryLvlDelegate(float batteryLevel);
public MainForm()
{
InitializeComponent();
}
public void setBatteryLvl(float batteryLevel)
{
if (InvokeRequired)
{
this.Invoke(new setBatteryLvlDelegate(setBatteryLvl), new object[] { batteryLevel });
}
this.batteryLvl.Text = batteryLevel.ToString();
}
}
}
Re: Changing GUI from another thread
If Invoke is required, then you properly fire off the cross thread invoke, then fall immediately into the direct access.
You need to fix this or ELSE ;):wave:
Re: Changing GUI from another thread
here is a simple example that may help you understand the nature of the problem...
Re: Changing GUI from another thread
Quote:
Originally Posted by
foamy
here is a simple example that may help you understand the nature of the problem...
that helped, but what about if the method is in another class?
Re: Changing GUI from another thread
Just make sure your UI class listens for the events that your delegate(s) fire, and react upon them. If you'd like, I might be able to dig up an example a little later on.
Re: Changing GUI from another thread
don't worry about it, i just passed the instance of the gui through all of the threads to end up at the last one