如果后台工作人员很忙,我如何告诉表单不要关闭?
How do i tell a form not to be close if a backgroundworker is busy?
private void ScanClouds_FormClosing(object sender, FormClosingEventArgs e)
{
backgroundWorker2.WorkerSupportsCancellation = true;
if (backgroundWorker2.IsBusy)
{
backgroundWorker2.CancelAsync();
}
Terminate();
}
除了调用 CancelAsync,我还想告诉表单不要关闭。
然后在完成的事件中我关闭表格:
private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
this.Close();
}
}
问题是当我点击关闭表格时,我如何告诉他不要关闭并在完成的事件中关闭它?
您可以将 OnFormClosing
method, to prevent the form from closing. Set e.Cancel
覆盖为 true
:
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (backgroundWorker2.IsBusy)
{
e.Cancel = true;
return;
}
base.OnFormClosing(e);
}
您可以在内部显示一个消息框或执行任何其他操作来通知用户您取消关闭的原因。
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (bgWorker.IsBusy)
e.Cancel = true;
}
拒绝执行用户操作是一种错误的形式。相反,您应该通过视觉反馈和线索表明该表单不可关闭。例如,将 ControlBox
设置为 False
,而后台作业为 运行。
您还可以让表单保持可关闭状态,并在表单关闭时中止后台任务。当然,这需要任务的合作(并非所有任务都可以中止)。
private void ScanClouds_FormClosing(object sender, FormClosingEventArgs e)
{
backgroundWorker2.WorkerSupportsCancellation = true;
if (backgroundWorker2.IsBusy)
{
backgroundWorker2.CancelAsync();
e.Cancel = true;
}
Terminate();
}
你也可以像上面那样在MyForm_FormClosing中写e.Cancel=true
,因为它也在内部调用表单的OnFormClosing方法。
private void ScanClouds_FormClosing(object sender, FormClosingEventArgs e)
{
backgroundWorker2.WorkerSupportsCancellation = true;
if (backgroundWorker2.IsBusy)
{
backgroundWorker2.CancelAsync();
}
Terminate();
}
除了调用 CancelAsync,我还想告诉表单不要关闭。 然后在完成的事件中我关闭表格:
private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
this.Close();
}
}
问题是当我点击关闭表格时,我如何告诉他不要关闭并在完成的事件中关闭它?
您可以将 OnFormClosing
method, to prevent the form from closing. Set e.Cancel
覆盖为 true
:
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (backgroundWorker2.IsBusy)
{
e.Cancel = true;
return;
}
base.OnFormClosing(e);
}
您可以在内部显示一个消息框或执行任何其他操作来通知用户您取消关闭的原因。
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (bgWorker.IsBusy)
e.Cancel = true;
}
拒绝执行用户操作是一种错误的形式。相反,您应该通过视觉反馈和线索表明该表单不可关闭。例如,将 ControlBox
设置为 False
,而后台作业为 运行。
您还可以让表单保持可关闭状态,并在表单关闭时中止后台任务。当然,这需要任务的合作(并非所有任务都可以中止)。
private void ScanClouds_FormClosing(object sender, FormClosingEventArgs e)
{
backgroundWorker2.WorkerSupportsCancellation = true;
if (backgroundWorker2.IsBusy)
{
backgroundWorker2.CancelAsync();
e.Cancel = true;
}
Terminate();
}
你也可以像上面那样在MyForm_FormClosing中写e.Cancel=true
,因为它也在内部调用表单的OnFormClosing方法。