BackgroundWorker杀死线程 [英] BackgroundWorker Kill thread

查看:72
本文介绍了BackgroundWorker杀死线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我有一个需求,例如我需要在主(父)窗口的帮助下打开4个子窗口.在主窗口中,我有一个组合框,其中有4个列表项.当我选择其中任何一个时,它将打开一个新窗口.假设当我选择一种形式的组合框具有1,2,3,4之类的选项时,它将显示第一个窗口,并且在执行第一个窗口时将执行的代码无论我需要同时打开第二个窗口.我可以关闭子窗口,但后台线程仍在运行.我有不同的方法,但是我无法终止线程进程.我如何取消进程并关闭表单.预先感谢...

问候,
Jeevan.

Hi All,
I have a requirement like i need to open 4 child windows with the help of main (parent) window. In main window i have a combo box it has 4 list items. When i select any one of them it will open a new window. Suppose combo box having options like 1,2,3,4 when i select 1 form that it will displayed first window and whatever the code will be executed while executing the first one i need to open simultaneously second one. I am able to close the child window but background the thread is still running. I have different ways but i am not able to kill the thread process. How can i kill the process and close the form. Thanks in an advance...

Regards,
Jeevan.

推荐答案

您可以使用BackgroundWorker并在您的工作程序代码中添加支持以进行取消.阅读这篇文章 [
You can use a BackgroundWorker and add support in your worker code for cancellation. Read this article[^] for an example.


为了使它更简单一点,请看下面的代码:
To make it a little more straight forward, look at the following code:
static void Main(string[] args)
{
    var bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.WorkerSupportsCancellation = true;
    bw.RunWorkerAsync();
    bw.CancelAsync();
    Console.ReadLine();
}

static void bw_DoWork(object sender, DoWorkEventArgs e)
{
    var bw = (BackgroundWorker) sender;
    while (!bw.CancellationPending)
    {
        //do work here
    }
    if (bw.CancellationPending)
    {
        e.Cancel = true;
    }
    else
    {
        bw.ReportProgress(100);
    }
}


还为FormClosing添加事件处理程序.如果后台线程正在运行,请取消它,在表单中设置一个标志,以记住您要稍后关闭它并取消表单关闭事件.

后台线程完成后,检查该标志,如果该标志已设置,则此时关闭表单.

如果取消花费的时间不多,则效果很好.否则,您可能需要在关闭表单之前将其隐藏.
Also add an event handler for FormClosing. If the background thread is running, cancel it, set a flag in the form to remember you want to close it later and cancel the form closing event.

When the background thread complete, check the flag and if the flag is set, then close the form at this point.

This works quite well if the cancellation does not take much time. Otherwise, you might want to hide the form before closing it.


这篇关于BackgroundWorker杀死线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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