I've been trying to implement multi-class-thread GUI management. As In I want different threads spread across multiple classes in different .cs files to update the UI as needed.
I've searched stackoverflow and other sources and found that most people use Dispatcher.Invoke or something similar. So I decided to start testing...
So below is a thread in a class called wThread.cs,
public class wThread
{
public EventHandler SignalLabelUpdate;
public Dispatcher uiUpdate;
public wThread()
{
uiUpdate = Program.myForm.dispat;
//the uiUpdate seems to be null for some reason... If i am doing it wrong how do i get the dispatcher?
Thread myThread = new Thread(run);
myThread.Start();
}
Action myDelegate = new Action(updateLabel);
// is there a way i can pass a string into the above so updatelabel will work?
public void updateLabel(String text)
{
if (SignalLabelUpdate != null)
SignalLabelUpdate(this, new TextChangedEvent(text));
}
public void run()
{
while (uiUpdate == null)
Thread.Sleep(500);
for (int i = 0; i < 1000; i++)
{
//I hope that the line below would work
uiUpdate.BeginInvoke(new Action(delegate() { Program.myForm.label1.Text = "count at " + i; }));
// was also hoping i can do the below commented code
// uiUpdate.Invoke(myDelegate)
Thread.Sleep(1000);
}
}
}
Below is my form1.cs it's the pre-loaded code from visual studio 2012,
public partial class Form1 : Form
{
public Dispatcher dispat;
public Form1()
{
dispat = Dispatcher.CurrentDispatcher;
InitializeComponent();
wThread worker = new wThread();
}
}
Most of my questions are in the comments above but here are them listed:
The uiUpdate seems to be null for some reason... If i am doing it wrong how do i get the dispatcher? (wThread.cs problem)
uiUpdate = Program.myForm.dispat'
Is there a way i can pass a string into the above so updatelabel will work?
Action myDelegate = new Action(updateLabel);
I hope that the line below would work
uiUpdate.BeginInvoke(new Action(delegate() { Program.myForm.label1.Text = "count at " + i; }));
Was also hoping i can do the below commented code
uiUpdate.Invoke(myDelegate)
EDIT: I moved the wThread constructor wThread worker = new wThread() out of the form1 initialization area... and it fixed my nullpointer. Instead I move the wThread constructor into the static main void where the form is constructed... like Application.Run(myForm);
Unfortunately the wThread will not start until I close the UI.. What is the best thing to do about this? Make another thread before the Application.Run starts my Form and use that thread to start my real thread?