Add a thread validation rule for usage of GetObjectForIUnknown
We run into a bug recently when we clean up code for other thread validation rules. Basically, add SwitchToUIThread to ensure code to use thread bound COM object on the UI thread.
However, this leads into exceptions like:
System.Runtime.InteropServices.COMException (0x8001010E): The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
That happens when a method takes an IntPtr parameter, and need convert it to COM object by calling GetObjectForIUnknown, which must happen on the calling thread. Adding SwitchToUIThread accidently pushes some of those calls to the UI thread, and potentially access a marshalled object on a wrong thread.
It appears this mistake has already been in a few other places in the codebase, and by updating code with existing threading rule, it may lead more mistakes in the future. (And hard to detect until a specific usage pops up.)
It would be worth to add a validation rule when the method has both switching thread calls & GetObjectForIUnknown. It is more difficult if the method switches thread, and passes the IntPtr to another method.
If we added an analyzer for this here, it wouldn't look for SwitchToUIThread, but rather SwitchToMainThreadAsync, so I don't know that it would help the CPS codebase.
I also suspect passing COM objects around as IntPtr to async methods is a very tiny use case for the general population.
Given these two points, the intersection seems to be very nearly zero folks who would benefit. Perhaps CPS defining their own analyzer that searches for their unique method name for switching threads and looking for calls to create RCWs would be more appropriate?