WPF在应用程序退出时取消backgroundworker [英] wpf cancel backgroundworker on application exits

查看:297
本文介绍了WPF在应用程序退出时取消backgroundworker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个主窗口,并在其中装入一个页面.用户按下按钮时,此页面将执行长时间的任务.我的问题是,当执行长任务并且用户按下主窗口的关闭按钮时,该应用程序似乎无法完成,因为我正在VS2008中对其进行调试,并且可以看到突出显示了停止按钮.如果要完成操作,必须按停止"按钮,应用程序不会在应用程序退出时自动停止调试.我以为.NET会在应用程序退出时自动停止后台工作,但是在看到这种行为后我不确定.我试图用以下方法强制和取消卸载事件页面中的后台工作程序:

In my application I have a main windows and into it, in a frame I load a page. This page do a long time task when the user press a button. My problem is that when long task is being doing and the user presses the close button of the main window, the application seems to not finish because I am debugging it in VS2008 and I can see the stop button highlighted. If I want to finish I have to press stop button, the application doesn't stop the debugging automatically on application exit. I thought .NET stops automatically backgroundworkers on application exits but I am not sure after seeing this behaviour. I have tried to force and cancel background worker in unloaded event page with something like this:

    private void Page_Unloaded(object sender, RoutedEventArgs e)
    {
        // Is the Background Worker do some work?
        if (My_BgWorker != null && My_BgWorker.IsBusy)
        {
            //If it supports cancellation, Cancel It
            if (My_BgWorker.WorkerSupportsCancellation)
            {
                // Tell the Background Worker to stop working.
                My_BgWorker.CancelAsync();
            }
        }


    }

,但没有成功.在执行CancelAsync()之后,几分钟后,我可以看到backgroundworker完成并引发RunWorkerCompleted,并且可以看到该事件已完成检查该事件中的e.Cancelled参数,但是执行了此事件后,该应用程序继续运行而没有退出,我已经不知道在做什么......

but with no success. After doing CancelAsync(), a few minutes after, I can see the backgroundworker finishes and raise RunWorkerCompleted and I can see the task is completed checking e.Cancelled argument in the event but after this event is exectued the application continues without exiting and I have no idea what is doing....

我将WorkerSupportsCancellation设置为true以支持一开始就取消.

I set WorkerSupportsCancellation to true to support cancel at the begining.

我很欣赏所有答案.谢谢.

I would apreciate all answers. Thanks.

推荐答案

取消不是自动的,DoWork事件处理程序中的代码需要通过检查CancellationPending属性的值来处理取消.调用CancelAsync不会终止线程,它只是将CancellationPending设置为true ...

Cancellation is not automatic, your code in the DoWork event handler needs to handle the cancellation by checking the value of the CancellationPending property. Calling CancelAsync doesn't abort the thread, it merely sets CancellationPending to true...

例如:

private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
    while(!bgw.CancellationPending)
    {
        ...
    }
}

这篇关于WPF在应用程序退出时取消backgroundworker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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