I am building a Windows Forms App, where I created a UserControl (called MyControl).
This UserControl can generate and return a value using a BackgroundWorker.
My question is, how can my form1 show in real-time the value produced by the UserControl when the calculation is completed?
public partial class MyControl : UserControl
{
BackgroundWorker bgWorker;
private string _num;
public string Num
{
get
{
return _num;
}
set
{
_num = value;
}
}
public MyControl()
{
InitializeComponent();
bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
}
void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate
{
//Done
MessageBox.Show(e.Result.ToString());
//↑↑↑↑↑ HERE
//I want to return to form1
// like to rewrite: form1.textbox1.text = e.Result.ToString();
});
btnStartAsyncOperation.Enabled = true;
btnCancel.Enabled = false;
}
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
string Num = A_huge_calculation();
e.Result = Num;
}
private void RunCalculate(string Num)
{
if (bgWorker.IsBusy != true)
{
bgWorker.RunWorkerAsync(Num);
}
}
private void btnStartAsyncOperation_Click(object sender, EventArgs e)
{
RunCalculate(_num);
}
}
}
Why use BackgroundWorker? Because it will do an unpredictable thing(like generate the MD5 and SHA1 checksum for any file), and I don't wanna the main form fell asleep for end user.
Besides form2 will addition this UserControl like form1, and assign unique control to show the value.
form2.cs
public partial class Form2 : Form
{
MyControl mycontrol;
private void Form2_Load(object sender, EventArgs e)
{
mycontrol.SentTO = 'richtextBox1';
//It can be assign any container name to receive the value when completed.
//when trigger the execute button inside the MyControl
}
private void button1_Click(object sender, EventArgs e)
{
mycontrol = new MyControl();
mycontrol.Num = "xxxxxx";
//run mycontrol
//mycontrol.run();
richtextBox2.Text = mycontrol.value; //Here, when the MyControl calculation is completed.
}
}
I also have been thinking to set a timer listen to this user control get value every 1000ms.
form1.cs
private void timer1_Tick(object sender, EventArgs e)
{
if( ! string.IsNullOrEmpty(mycontrol.value))
{
richtextBox2.Text = mycontrol.value; //here is when the MyControl calculation is completed.
timer1.Stop();
}
}
The old ideal was to access the public value of MyControl by a timer,
when MyControl completed, it will return a non-null value, and the timer stop MyControl detection.
But it will derivative why the MyControl can know what is the timer name in form1?
Or form1 be set two or more MyControls, needs more timers to detect every MyControl.