Why does Thread.Join () freeze even though the methods in the thread have returned?

I have a WPF application that uses some library code for authentication, which must be executed in a single-threaded apartment thread. My approach is to create a separate thread to get the authentication object, block until the thread returns, and then continue execution. However, in some cases, my application freezes in Thread.Join (), although 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; } 

I am new to both mulththreading and WPF, so I could do something stupid. Does anyone see what is going on here? For recording, I have no problem if I do not install the stream in the STA, but this is a requirement.

[Edit: It seems that the error only occurs when the specified method is called using the check binding in the WPF view, especially in the TextBox. When I call the same code in the view constructor, the code works as expected. That would be a viable workaround, but it would be interesting to know what was really going on here.]

[Edit: here, the code was simplified for debugging - in the production code, the thread method is inside the AuthThreadWorker object, which allows you to return the result of the authentication process to the authResult object. But this data, as far as I can tell, is not related to freezing, since freezing occurs even in simplified code.]

+4
source share
1 answer

Based on your code; it looks like you are doing it right, but the thread never REALLY ends. Try setting a breakpoint in the END function in the stream; instead of the return keyword (in case you are doing some processing in your return statement that prevents the thread from exiting), as shown in the figure below enter image description here . Naming the thread using authenticationThread.Name (or mthread.Name, as shown in the example) can also help with debugging. If the thread is REALLY completed, you should see "Thread" Your name "(0x143c) came up with code 0 (0x0)". in the output window of Visual Studio.

+7
source

All Articles