You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何取消BackgroundWorker并设置IsBusy为false?重启逻辑遇阻求助

BackgroundWorker CancelAsync() 未更新IsBusy属性的问题及解决办法

在WinForms中调用CancelAsync()取消BackgroundWorker时,该方法并不会立即将worker的IsBusy属性设置为false。我需要在取消worker并完成部分后续操作后重启它,因此通过IsBusy属性判断worker是否已关闭,再执行重启操作,但实际判断时worker仍处于Busy状态,导致无法正常重启。

相关代码示例如下:

private void buttonStart_Click(object sender, EventArgs e)
{
    backgroundWorker1.WorkerSupportsCancellation = true;

    if (!backgroundWorker1.IsBusy)
    {
        backgroundWorker1.RunWorkerAsync();
        buttonStart.Enabled = false;
    }
}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    BackgroundWorker worker = (BackgroundWorker)sender;

    while (!worker.CancellationPending)
    {
        // 执行具体工作
    }
}

private void buttonRestart_Click(object sender, EventArgs e)
{
    if (backgroundWorker1.WorkerSupportsCancellation && backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
        buttonStart.Enabled = true;
    }

    // 执行一些后续操作
    // ...

    if (!backgroundWorker1.IsBusy)    // 此处worker仍处于Busy状态
    {
        backgroundWorker1.RunWorkerAsync();
    }
}

解决更新说明

经过大量排查和调试,未找到直接解决BackgroundWorker该问题的方案,但发现BackgroundWorker(简称BGW)是随.NET 2.0发布的老旧组件,已逐渐被Task/await异步模式替代。将代码从BackgroundWorker迁移到异步任务实现后,功能恢复正常且符合预期。

内容的提问来源于stack exchange,提问作者Slash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 03:13:26