[MS] The useless IMemory­Buffer­Reference.Closed event - devamazonaws.blogspot.com

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.


Post Updated on January 23, 2024 at 03:00PM
Thanks for reading
from devamazonaws.blogspot.com

Comments

Popular posts from this blog

Scenarios capability now generally available for Amazon Q in QuickSight - devamazonaws.blogspot.com

[MS] Introducing Pull Request Annotation for CodeQL and Dependency Scanning in GitHub Advanced Security for Azure DevOps - devamazonaws.blogspot.com

AWS Console Mobile Application adds support for Amazon Lightsail - devamazonaws.blogspot.com