The useless IMemory­Buffer­Reference.Closed event

Raymond Chen

The IMemory­Buffer­Reference interface has a Closed event which is signaled when the underlying object is closed or destructed. Closing the IMemory­Buffer­Reference invalidates any pointers that had been obtained from GetBuffer.

Unfortunately, this event is basically useless.

The idea was that a consumer of the buffer could be notified that the underlying data has been made unavailable, but multithreading means that this notification doesn’t really help: Suppose that you have one thread that is doing some computation with the buffer, and another thread that notifies you that the buffer is invalid. The notification thread can’t stop the computation thread in its tracks. At best, it would have to signal the computation thread to wrap up and block the notification thread until the computation thread reports that it has stopped accessing the buffer. But the notification might be delivered on a single-threaded apartment, in which case blocking is ill-advised.

What’s worse, some implementations of IMemory­Buffer­Reference raise the event after the buffer becomes invalid, so this event doesn’t even give you a chance to stop your computation. It’s just telling you, “Oh, hey, so, like, you probably just corrupted memory a few millseconds ago.”

Fortunately, you don’t really need the notification because you’re generally just notifying yourself. Each IMemory­Buffer­Reference is a separate reference to the buffer, and if you have two components that want to access the buffer, you can just give each one a different IMemory­Buffer­Reference. That way, one component closing the IMemory­Buffer­Reference has no effect on the other. The only time your IMemory­Buffer­Reference should be closed is when you close it.

And hopefully you can arrange so that you never surprise yourself.

Next time, we’ll look at how the Closed event is not merely useless but also dangerous.

1 comment

Discussion is closed. Login to edit/delete existing comments.

  • 3xtant 0

    I am very sorry for leaving a completely unrelated comment here, but I wanted to refer to your seminal post on notification icons using UIAutomation. I don’t think it is an exaggeration to say that most accessible apps or those that use automation for other purposes started with those helper methods you wrote back then.

    Having said that, I ask if you would please consider creating an updated post for Windows 11, apparently after version 22H2, when those methods broke for good. The notification area is not the User/System Promoted Notification Area anymore, and the chevron is now identified as a button that says “Show hidden icons” or “Hide”, depending on its state. I think it’ll serve as the seminal post for accessibility involving the notification icons in Windows 11.

    Thanks for your posts, they are always interesting and fun to read.

Feedback usabilla icon