在按钮单击事件中中止长时间运行的线程 [英] Abort long running thread in button click event

查看:58
本文介绍了在按钮单击事件中中止长时间运行的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF应用程序中,我运行很长时间,该过程使用BlueBeam Q Server将文件转换为PDF.当该过程发生时,它不应冻结,因此编写了以下代码来解决该问题:

In my WPF application, I have a long running process which converts files to PDFs using BlueBeam Q Server. When the process takes place, it should not freeze, so the below code has written to take care of that:

private void btn_convert_Click(object sender, RoutedEventArgs e)
{
        thread = new Thread(new ThreadStart(WorkerMethod));
        thread.SetApartmentState(ApartmentState.STA);
        thread.IsBackground = true;
        thread.Name = "PDF";
        thread.Start();
}

WorkerMethod()
{
//code to connect to Q server and conversion goes here
}

现在,当过程开始时,取消按钮将对用户可见.当用户按下取消时,我想中止启动的线程.我写的代码如下:

Now, when the process starts, a cancel button will be visible to the user. When the user presses cancel, I want to abort the thread started. I wrote the code as below:

private void btn_cancel_Click(object sender, RoutedEventArgs e)
    {
        if (thread.Name == "PDF")
            thread.Abort(); 
    }

但是该线程不会中止并继续执行该过程.请给我您的宝贵建议.

But the thread doesn't abort and continues the process. Please give me your valuable suggestions.

推荐答案

您应尽可能避免使用Abort.在SO中搜索如何优雅地取消线程-当线程代码调用您无法影响的其他代码(例如第三方库方法或类似方法)时,将无法执行此操作.

You should avoid Abort whenever possible. Search SO for how to cancel threads gracefully - which can not be done when the thread code calls other code you can not influence, like a third party library method or something like that.

例如,如果您的线程方法执行以下操作:

For example if your thread method does something like this:

WorkerMethod()
{
    CallFunctionInExternalDLL();
}

无法正常终止.

要取消"该线程,最好指示该线程应取消(例如,使用bool标志)并使该线程回滚其结果(例如,删除创建的PDF或其他内容)像那样).然后,您的应用程序就可以继续运行,就好像从未启动线程一样.

To "cancel" such a thread, it's best to indicate to the thread it should cancel (using a bool flag, for example) and have the thread roll back its result (for example, delete a created PDF or things like that). Your application could then just continue as if the thread had never been started.

例如,您的代码可能如下所示:

For example your code could then look like this:

WorkerMethod()
{
    CallFunctionInExternalDLL();
    if (m_threadAborted)
        RollBackWhatFunctionDid();
}

如果您的线程如下所示:

If your thread looks like this:

WorkerMethod()
{
    while (true)
    {
        CallFunctionInExternalDLL();
    }
}

您可以这样做:

WorkerMethod()
{
    while (!m_threadAborted)
    {
        CallFunctionInExternalDLL();
    }

    if (m_threadAborted)
        RollBackStuff();
}

在这些示例中,m_threadAborted是这样声明的bool标志:

In these examples, m_threadAborted is a bool flag declared like this:

private volatile bool m_threadAborted = false;

这篇关于在按钮单击事件中中止长时间运行的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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