title: Why does Thread.Join() hang even though the methods in the thread have returned?
body: <p>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 <em>some</em> instances my application hangs on Thread.Join(), even though the thread method has returned.</p>
  
  <pre><code>    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;
      }
  </code></pre>
  
  <p>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.</p>
  
  <p>[Edit: It appears that the error only occurs when I call the specified method through a validation binding in a WPF view, specifically on a TextBox. When I call the same code in the constructor of the view, the code runs as expected. This would be a viable workaround, but it would be interesting to know what's actually going on here.]</p>
  
  <p>[Edit: The code here has been simplified a bit for debugging - in the production code, the thread method is inside an AuthThreadWorker object which enables returning the result of the authentication process to the authResult object. But these details are as far as I can tell unrelated to the freeze, as the freeze occurs even in the simplified code.]</p>