我正在构建Windows窗体应用程序,并在其中创建了UserControl(称为MyControl
)。
此UserControl可以使用BackgroundWorker
生成并返回一个值。
我的问题是,我的form1
如何在计算完成后实时显示UserControl产生的值?
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);
}
}
}
为什么使用BackgroundWorker
?因为它将做不可预测的事情(例如为任何文件生成MD5和SHA1校验和),而且我不想让最终用户睡着的主要形式。
除了form2之外,还将像Form1一样添加此UserControl,并分配唯一控件以显示该值。
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.
}
}
我还一直在考虑设置一个计时器,以每1000毫秒侦听此用户控件获取值。
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();
}
}
过去的理想是通过MyControl
来访问timer
的公共价值,
MyControl
完成后,它将返回非null值,并且timer
停止MyControl
检测。
但是,这将衍生出为什么MyControl
可以知道timer
中的form1
名称是什么?
或将form1
设置为两个或更多MyControls
,则需要更多timers
来检测每个MyControl
。