Thursday, September 23, 2004

Update on the Windows Forms Delayed Handle Creation Bug

I got an email about a week from a fellow called Jeff Berkowitz who had experienced the same problem with the delayed window handle creation that I posted on here. Jeff's post of 9 Aug 2003 describes his discovery of the problem, and in his email he references this incredible detailed review of the problem by Justin Rogers.

The situation is a bit of a chicken-and-the-egg-scenario. My initial thoughts were to marshal back to the Control-creating thread to create the handle, but you need the handle to get back onto that thread. PostThreadMessage won't do the trick, because its message can get lost when delivered to a UI thread is in a modal loop. If the original UI thread had a thread-specific hook installed, PostThreadMessage is feasible as the PostThreadMessage message won't get lost, but is this getting too far-out?

Here is the response we got from the Windows Forms team on the bug:

We had thought about storing the creation thread for the control, but when we do eventually perform an Invoke, the invocation must actually use the control’s HWND to marshal the call to the correct thread. Therefore, if the HWND isn’t created we cannot marshal the call.

The breaking change police may shoot it down, but the best behavior we can shoot for I think is to throw in Invoke whenever the handle isn’t created. Ideally we would store the creation thread at startup so we could make IsInvokeRequired correctly. Adding another four bites to Control isn’t a good solution, but we have some optimized ways of storing data so it’s only four bytes if (a) you ask IsInvokeRequired and (b) we can clean it up when the HWND is created.

If that gets shot down I’ll pursue the documentation of IsHandleCreated along with IsInvokeRequired. Better than nothing, I guess.

Anyway, as the work-around of referencing the Handle property before doing asynch. stuff is so trivial, as long as Whidbey raises an exception to let the developer know something is wrong, I'll be happy (or at least not sad).


Post a Comment

<< Home