gpt4 book ai didi

C#,后台 worker

转载 作者:行者123 更新时间:2023-11-30 14:16:28 27 4
gpt4 key购买 nike

我有一个使用 BackgroundWorker 组件的示例 WinForms 应用程序。它工作正常,但是当我点击 Cancel 按钮取消后台线程时,它并没有取消线程。当我点击 Cancel 按钮调用 .CancelAsync() 方法时,然后在 RunWorkerCompleted 事件处理程序中 e.Cancelled属性始终保持 false。我想当我点击 Cancel 按钮时,它应该设置为 true。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
// Wait 100 milliseconds.
Thread.Sleep(100);
// Report progress.
if (backgroundWorker1.CancellationPending == true)
{
//label1.Text = "Cancelled by user.";
break;
}

backgroundWorker1.ReportProgress(i);
}
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
label1.Text = e.ProgressPercentage.ToString();
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
label1.Text = "Canceled!";
}
else if (e.Error != null)
{
label1.Text = "Error: " + e.Error.Message;
}
else
{
label1.Text = "Done!";
}
}

private void button2_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
// Cancel the asynchronous operation.
backgroundWorker1.CancelAsync();
}
}

最佳答案

Canceled 属性仍然为 false,因为您跳出循环,然后允许 backgroundworker 的 DoWork 函数以正常方式结束。您永远不会告诉您的后台工作人员组件实际接受了挂起的取消。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
// Wait 100 milliseconds.
Thread.Sleep(100);

if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
break;
}

// Report progress.
backgroundWorker1.ReportProgress(i);
}
}

区别很重要,因为有时您可能希望在检测到 CancellationPending 请求时回滚已经完成的工作,因此可能需要一段时间才能真正完成取消。

关于C#,后台 worker ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7471470/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com