ive searched high and low for invoke required related posts on stack overflow.. its helped me learn a lot.. but i have a couple of questions.. not only relating to invoke required but also background worker.. bear with me please.. :)
my application does something long and needs to update the gui in the process (progress bar, status bar, text boxes).. i used a thread but it gave the dreaded cross-thread exception when updating the UI.. i recently (kinda) got the hang of using invokerequired properly..[Automating the InvokeRequired code pattern].. the code ive used from this post is:
public static partial class CHelper
{
public static void InvokeIfRequired(this Control oCtrl, MethodInvoker fnAction)
{
if (oCtrl.InvokeRequired)
{
oCtrl.Invoke(fnAction);
}
else
{
fnAction();
}
}
}
public partial class Form1 : Form
{
public void Test()
{
this.InvokeIfRequired(() =>
{
Text = "Window Title";
button1.Text = "Hello";
});
button1.InvokeIfRequired(() =>
{
Text = "Window Title";
button1.Text = "Hello";
});
}
}
now here's something i noticed.. this.InvokeIfRequired and button1.InvokeIfRequired both do the same thing.. why is this so? i was expecting that the Text in button1.InvokeIfRequired would correspond to button1's text property.. but instead it refers to the parent form's.. to me this seems silly, unintuitive, and wrong.. or maybe im doing something wrong..
another question.. i didnt get the hang of invokerequired back then so i resorted to using background worker.. and using progress event to update the gui..
public partial class Form1 : Form
{
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(0, "Hello World");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState != null)
{
button1.Text = e.UserState as string;
}
}
}
so far, it hasnt caused me problems.. i wanna know which of these two approaches is better? and why? also, is there a way to pass data to the prevous InvokeIfRequired function?
thanks.. =)
edit 01: Is there any difference between using Invoke for the parent form or for the target control?.. yes form.invoke and control.invoke is the same.. but why should it be? its not intuitive, and gives the wrong impression..