views:

80

answers:

1

I am creating a managed WPF UI front-end to a legacy Win32-application. The WPF front-end is the executable; as part of its startup routines I start the legacy app as a DLL in a second thread. Any UI-operation (including CreateWindowsEx, etc.) by the legacy app is invoked back on the main UI-thread.

As part of the shutdown process of the app I want to clean up properly. Among other things, I want to call DestroyWindow on all unmanaged windows, so they can properly clean themselves up. Thus, during shutdown I use EnumWindows to try to find all my unmanaged windows. Then I call DestroyWindow one the list I generate. These run on the main UI-thread.

After this background knowledge, on to my actual question:
In the enumeration procedure of EnumWindows, I have to check if one of the returned top-level windows is one of my unmanaged windows. I do this by calling GetWindowThreadProcessId to get the process id and thread id of the window's creator. I can compare the process id with Process.GetCurrentProcess().Id to check if my app created it.

For additional security, I also want to see if my main UI-thread created the window. However, the returned thread id is the OS's ThreadId (which is different than the managed thread id). As explained in this question, the CLR reserves the right to re-schedule the managed thread to different OS threads. Can I rely on the CLR to be "smart enough" to never do this for the main UI thread (due to thread-affinity of the UI)? Then I could call GetCurrentThreadId to get the main UI-thread's unmanaged thread id for comparison.

+1  A: 

The ability to map a managed thread to a custom threading scheme was introduced in .NET 2.0 for custom CLR hosts. Specifically, SQL Server. They wanted to use fibers, a native feature of SQL Server. They couldn't make a go of it, the project was shelved. There are no CLR hosts that I'm aware of right now that actually take advantage of the feature.

It will never be an issue in the default CLR host, the one you get in a WPF app. A managed thread always maps to one OS thread and does so consistently. You can rely on the value returned by GetCurrentThreadId(). I seriously doubt that will ever change, it would be a major breaking change. This isn't likely to be true to some kind of future host, similar to Silverlight, but your code will never get close to that.

Hans Passant
That sounds like what I expected. I assume there is no official/semi-official statement on this anywhere?
Daniel Rose
Of course not. You'd have to call Microsoft Support to nail that jelly to a wall.
Hans Passant