为什么的Thread.join()挂即使在线程的方法已经回来了? [英] Why does Thread.Join() hang even though the methods in the thread have returned?

查看:194
本文介绍了为什么的Thread.join()挂即使在线程的方法已经回来了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了一些库代码,这就需要在单线程公寓线程中运行验证一个WPF应用程序。我的做法是产卵一个单独的线程来获取认证对象,块直到线程返回,然后继续执行。然而,在部分的情况下,我的应用程序挂起的Thread.join(),即使已返回线程的方法。

I have a WPF application which uses some library code for authentication which needs to run in a Single-Thread Apartment thread. My approach is to spawn a separate thread to get the authentication object, block until the thread returns and then continue execution. However, in some instances my application hangs on Thread.Join(), even though the thread method has returned.

    public static ClaimsAuthenticationResult GetClientContextAndCookieCollection(string siteUrl, out CookieCollection cookieResult)
    {
        ClaimsAuthenticationResult authResult = new ClaimsAuthenticationResult();

        // Authentication module needs to run in single-thread apartment state because it uses
        // COM library calls where this is required
        Thread authenticationThread = new Thread(new ThreadStart(threadMethod));
        authenticationThread.SetApartmentState(ApartmentState.STA);
        authenticationThread.Start();

        // Block until thread completion
        authenticationThread.Join(); // Application hangs here

        return authResult;
    }

    private static void threadMethod() {
        // In proper application: set result. But for debugging, return immediately
        return;
    }



我是新来的都mulththreading和WPF,所以我可能会做一些愚蠢的。有谁看到是怎么回事?对于记录,如果我不设置线程STA我不明白的问题,但这是一个必要条件。

I am new to both mulththreading and WPF, so I might be doing something stupid. Does anyone see what's going on here? For the record, I don't get the problem if I don't set the thread to STA, but this is a requirement.

推荐答案

基于您的代码;它看起来好像你做正确,但线程从来没有真正结束。尝试在该线程函数的结尾设置断点;而不是return关键字(如果你正在做某种处理以防止该线程从退出的return语句),如下面
图片。使用命名的authenticationThread.Name线程(或mthread.Name如图所示例子)也可以帮助调试。如果线程终止真的,你应该看到线程提供yourname'(0x143c)已退出,代码为0(为0x0)。在Visual Studio中的输出窗口。

Based on your code; it looks as if you're doing it correctly, but the thread is never REALLY terminating. Try setting a breakpoint at the END of the function in the thread; instead of the return keyword (in case you're doing some kind of processing in your return statement that prevents the thread from exiting), as shown in the picture below . Naming the thread using authenticationThread.Name (or mthread.Name as shown in example) can also aid with debugging. If the thread REALLY terminated, you should see "The thread 'yourname' (0x143c) has exited with code 0 (0x0)." in the Output window of Visual Studio.

这篇关于为什么的Thread.join()挂即使在线程的方法已经回来了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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