What are the thread safety requirements of HSTRING and BSTR?

They do not have thread affinity. The post What are the thread safety requirements of HSTRING and BSTR? appeared first on The Old New Thing.

Mar 14, 2025 - 18:14
 0
What are the thread safety requirements of HSTRING and BSTR?

Among the proliferation of string types are the HSTRING (represented in C++/WinRT as winrt::hstring and in C++/CX as String^) and the BSTR. What are the threading rules for these string types?

These string types are not COM objects, so the restrictions on COM objects do not apply. These are just blocks of memory that have freestanding functions for manipulating them (such as Sys­Alloc­String and Sys­Free­String for BSTR; Windows­Create­String and Windows­Delete­String for HSTRING). You are welcome to call any method from any thread.

The rules for BSTR are that read operations (like Sys­Get­String­Len) can operate concurrently. But no read operations can operate concurrently with a write operation, so you cannot do a Sys­Get­String­Len at the same time as a Sys­Re­Alloc­String, for example, and you can’t modify the string contents on one thread while reading them from another.

Windows Runtime HSTRINGs are immutable, so there are no write operations. This makes the rules simpler: Once you create an HSTRING (until you destroy it), all operations are thread-safe.

The post What are the thread safety requirements of HSTRING and BSTR? appeared first on The Old New Thing.