如何与QUOT;杀"后台工作完全? [英] How to "kill" background worker completely?

查看:124
本文介绍了如何与QUOT;杀"后台工作完全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写重复运行数字IO操作的顺序Windows应用程序。

I am writing a windows application that runs a sequence of digital IO actions repeatedly.

行动这个序列开始,当用户点击开始按钮,它是由后台工作在backgroundWorker1_DoWork()。

This sequence of actions starts when the user click a "START" button, and it is done by a background worker in backgroundWorker1_DoWork().

不过,也有几次,当我拿到这BackgroundWorker的正忙......。的错误消息。

However, there are occasions when I get the "This backgroundworker is currently busy......." error message.

我,用whil​​e循环开始行动的另一个序列之前,杀的背景工人思想落实在code以下内容:

I am thinking of implementing the following in the code, by using a while loop to "kill" the background worker before starting another sequence of action:

if (backgroundWorker1.IsBusy == true)
{

    backgroundWorker1.CancelAsync();
    while (backgroundWorker1.IsBusy == true)
    {
        backgroundWorker1.CancelAsync();
    }

    backgroundWorker1.Dispose();

}

backgroundWorker1.RunWorkerAsync();

我想我主要关注的是,将backgroundWorker1被封杀最后?如果会,会不会需要很长的时间去完成它?

I think my main concern is, will the backgroundWorker1 be "killed" eventually? If it will, will it take a long time to complete it?

这个编码将让我进入一个无限循环?

Will this coding get me into an infinite loop?

推荐答案

您可以使用这样的事情(更多有关中止管理线程和有关ThreadAbortException看的Plumbing的ThreadAbortException深处使用转子由克里斯·塞尔斯):

You can use something like this (for more information about aborting managed threads and about ThreadAbortException see "Plumbing the Depths of the ThreadAbortException Using Rotor" by Chris Sells):

public class AbortableBackgroundWorker : BackgroundWorker
{

    private Thread workerThread;

    protected override void OnDoWork(DoWorkEventArgs e)
    {
        workerThread = Thread.CurrentThread;
        try
        {
            base.OnDoWork(e);
        }
        catch (ThreadAbortException)
        {
            e.Cancel = true; //We must set Cancel property to true!
            Thread.ResetAbort(); //Prevents ThreadAbortException propagation
        }
    }


    public void Abort()
    {
        if (workerThread != null)
        {
            workerThread.Abort();
            workerThread = null;
        }
    }
}

用法:

backgroundWorker1 = new AbortableBackgroundWorker();
//...
backgroundWorker1.RunWorkerAsync();

if (backgroundWorker1.IsBusy == true)
{
    backgroundWorker1.Abort();
    backgroundWorker1.Dispose();
}

这篇关于如何与QUOT;杀"后台工作完全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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