views:

176

answers:

1

I am debugging an app that is (mostly) a Winforms UI on top of unmanaged code. A little bit of the UI code is not WinForms: it is using DirectX to draw directly onto the surface of some Panel components. In order to do so, the windows handle of the component is recorded after it is created, and any subsequent calls requiring a handle that the module performing this DirectX display needs (e.g. GetWindowRect()), uses this handle. This mechanism has been in place for some time, without seeing the problem I am about to describe, although maybe we were just lucky. The programmer who put this in place is no longer available to me.

The problem I am trying to solve is that, very intermittently, the display for this area gets corrupted. This routine is getting called from a background thread. I have seen in my app log that, for example, the call to GetWindowRect() will suddenly, and concomitant with the drawing problem, return garbage coordinates. The Window handle itself is uncorrupted and I am reasonably sure that we have not overwritten the Windows data structure; I can stop and restart our display stream, and GetWindowsRect() will, using that same Windows handle, start returning good coordinates again.

If this were at the .NET level, I would use Invoke to defer the draw to the main thread. My question is, should we be doing the same for this DirectX call? I was trying to find the Microsoft admonition about not drawing in background threads, to remind myself whether it extends to using Windows handles; can anyone point me to this?

PC

A: 

Window handles have thread affinity.

The most important user interface element is of course the window. Window objects have thread affinity. The thread that creates a window is the one with which the window has an inseparable relationship. Informally, one says that the thread "owns" the window. Messages are dispatched to a window procedure only on the thread that owns it, and generally speaking, modifications to a window should be made only from the thread that owns it. Although the window manager permits any thread to access such things as window properties, styles, and other attributes such as the window procedure, and such accesses are thread safe from the window manager's point of view, load-modify-write sequences should typically be restricted to the owner thread.

1800 INFORMATION