使用标志退出BackgroundWorker

4 c# multithreading backgroundworker

想象一下,我有这样的代码:

 private bool flag = false;
 public SomeClass()
 {
     public void setup()
    {
        worker = new BackgroundWorker();
        worker.DoWork += worker_DoWork;

        if(!worker.IsBusy)
            worker.RunWorkerAsync();
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        if(flag == true)
          return;
        //whatever You want the background thread to do...
        SomeClass.SomeStaticMethodWhichHasLoopInside();
    }
}
Run Code Online (Sandbox Code Playgroud)

当用户单击我的应用程序中的"退出"按钮时,我可以设置flag=true内部 - 这是停止线程启动的正确方法BackgroundWorker吗?我想只在应用程序想要退出时才这样做 - 这样我就停止了线程.或者会被自动杀死?

Sri*_*vel 7

不,不要这样做.它不会按预期工作.你的flag领域甚至没有被宣布为volatile; 有可能该字段的真值尚未刷新到内存中.其他线程仍然会看到flag它是错误的,因为它缓存了自己的值副本,并且BackgroundWorker可能永远不会结束.

相反,只需调用BackgroundWorker.CancelAsync并在事件处理程序中检查BackgroundWorker.CancellationPending boolean DoWork.

private void OnExit(..)
{
    worker.CancelAsync();
}
Run Code Online (Sandbox Code Playgroud)

所以你的DoWork方法将成为

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    while(!worker.CancellationPending)
    {
        //whatever You want the background thread to do...
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您没有循环,则需要CancellationPending不时检查属性.

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    if(worker.CancellationPending)
        return;
    //Do something..
    if(worker.CancellationPending)
        return;
    //Do some other thing..
    if(worker.CancellationPending)
        return;
    //Do something else..
}
Run Code Online (Sandbox Code Playgroud)

我想只在应用程序想要退出时才这样做 - 这样我就停止了线程.或者会被自动杀死?

它将被CLR自动杀死,因为该线程是后台线程.但是,不要依赖这个事实,因为我们不知道在CLR杀死线程时你的线程将执行什么.例如,它可能一直在写一个文件,在这种情况下你将留下损坏的文件.

后果甚至可能更糟,因此始终建议您自己优雅地停止线程.

问题在评论中提出:如何在循环使用其他方法时取消?

看来你正在使用.Net4.5.你可以利用CancellationTokenSource和CancellationToken.此外,您可以考虑使用TPL和async-await功能,这将使您的生活更轻松.

private CancellationTokenSource tokenSource = new CancellationTokenSource();

private void OnExit(..)
{
    tokenSource.Cancel();
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    //whatever You want the background thread to do...
    SomeClass.SomeStaticMethodWhichHasLoopInside(tokenSource.Token);
}

class SomeClass
{
    public static void SomeStaticMethodWhichHasLoopInside(CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            //Do something
        }
    }
}
Run Code Online (Sandbox Code Playgroud)