Wednesday, April 29, 2015

Don't Set the Thread Desktop from Thread Pool Threads

A month or so ago, I had written a .NET method that used Task.Factory.StartNew to show a form on an alternate desktop. I used P/Invoke to call SetThreadDesktop on that other thread before showing the form with Application.Run. I then waited for the thread to end by calling Wait on the returned Task. Once that finished, I switched the user's desktop back to the normal one and then closed the temporary desktop.

The problem was that the CloseDesktop call always failed with a Win32 error indicating that the resource was in use. After pondering that for a moment, I realized that my method of creating a new "thread" just borrowed a .NET thread pool thread and run my code on it for a while. As Raymond Chen says, using the thread pool is like renting a house - don't go changing the carpet. I had been changing the desktop of a random thread pool thread, which of course stuck around and continued being on it, causing the error.

The fix was to use New Thread to force the creation of a thread completely under my control.

No comments:

Post a Comment