我有一个 Windows 窗体可以打开另一个窗体。在次要形式中,它异步启动任务。如果用户启动任务然后取消它并快速关闭表单,表单将被处理并设置为 null 但是当任务从被取消中恢复时我仍然会收到 MessageBox.Show 发生
public class MyMainForm : Form
{
public void OpenChildForm()
{
MyChildForm form = new MyChildForm();
form.ShowDialog();
form.Dispose();
form = null;
}
}
public class MyChildForm : Form
{
private CancellationTokenSource MyTokensource;
private Task task;
public void StartTask()
{
MyTokensource = new CancellationTokenSource();
task = Task.Factory.StartNew(() => MyMethod(MyTokensource.Token), MyTokensource.Token);
}
public void MyMethod(CancellationToken token)
{
var result = StaticClass.DoSomethingLengthy(token); //The cancel make take a couple of seconds to return here
if (result == Cancelled)
{
MessageBox.Show("Cancelled");
UpdateLabel("Cancelled")
}
}
public void ButtonClose_Click()
{
if (task != null && !task.IsCompleted)
{
MyTokensource.Cancel();
}
this.Close();
}
}
最佳答案
the form is Disposed and set to null however when the task comes back from being cancelled I still get a MessageBox.Show happen
将作为表单引用的变量设置为 null,甚至在表单上调用 Dispose(),实际上销毁表单。 Task 仍在执行,直到它被取消(CancellationTokenSource
被设计为用于取消的协作模型)。
因此,您需要显式处理取消任务时出现的代码路径。这可能就像检查您是否已经处置一样简单,即:
if (this.IsDisposed)
return; // Just break out if we canceled and shut down
// Your other code....
if (result == Cancelled)
MessageBox.Show("Cancelled");
关于c# - 保持 Form 实例打开的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9687404/