为什么总是BackgroundWorker的忙? [英] Why BackgroundWorker always is busy?

查看:517
本文介绍了为什么总是BackgroundWorker的忙?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到在我的WPF应用程序东西在我的后台工作怪怪的。

I realized something strange in my background worker in my WPF application.

我想要,现在做到的是等到BW完成再掀。螺纹

What I'm trying to accomplish right now is to wait until the BW finishes to start another thread.

检查下面的代码:

if (bw.IsBusy)
{
    bw.CancelAsync();

    System.Threading.ThreadStart WaitThread = 
        new System.Threading.ThreadStart(delegate() {
            while (bw.IsBusy)
            {
                System.Threading.Thread.Sleep(100);
            }

            bw.RunWorkerAsync();
        });

    System.Windows.Application.Current.Dispatcher.Invoke(
        System.Windows.Threading.DispatcherPriority.Normal,
        WaitThread);  // if I remove this line, bw fires RunWorkerAsyncEvent
}
else
{
    bw.RunWorkerAsync();
}

请注意,我添加了一个Dispatcher.Invoke等到体重不如果我调用它,不会触发 RunWorkerAsyncCompleted 事件忙碌,但所有的时间都很忙。虽然,如果我删除这一行,火灾事件,这真的奇怪。

Please note that I added a Dispatcher.Invoke to wait until the bw is not busy, but ALL THE TIME IS BUSY if I Invoke it and never fires the RunWorkerAsyncCompleted event. Although,, if I remove that line, FIRES the event and it's really strange that.

我怎样才能等到体重结束?

How can I wait until the bw finishes?

推荐答案

这就是所谓的僵局,一个很常见的线程问题。该BGW不能停止忙碌,直到RunWorkerCompleted事件运行。你的应用程序的主线程事件运行,它可以在你的主线程是不是忙着做别的事情只能运行。它被闲置,调度循环中运行。

This is called "deadlock", a very common threading problem. The BGW cannot stop being busy until the RunWorkerCompleted event runs. That event runs on your app's main thread, it can only run when your main thread isn't busy doing something else. It has to be idle, running inside the dispatcher loop.

但你的主线程并没有闲着,它卡在while()循环等待IsBusy返回false里面。因此事件永远不能运行,因为主线程忙等待BGW来完成,BGW无法完成,因为主线程从不闲着。 致命拥抱,又名僵局。

But your main thread isn't idle, it is stuck inside the while() loop waiting for IsBusy to return false. So the event can never run since the main thread is busy waiting for the BGW to complete, the BGW cannot complete because the main thread never goes idle. "Deadly embrace", aka deadlock.

您将有不同的做到这一点,你不能等待。通过创建BGW的另一个实例说。或者只是不允许此代码,直到RWC事件触发运行。或通过设置标志,由RunWorkerCompleted事件处理程序,然后可以重新开始测试BGW

You will have to do this differently, you cannot wait. Say by creating another instance of BGW. Or just not allowing this code to run until the RWC event fires. Or by setting a flag, tested by the RunWorkerCompleted event handler which can then start the BGW again.

这篇关于为什么总是BackgroundWorker的忙?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆