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.
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. https://devblogs.microsoft.com/oldnewthing/20141013-00/?p=43863
Having said that, I ask if you would please consider creating an updated post for Windows 11, apparently after version...