InvalidCastException: RPC_E_CANTCALLOUT_ININPUTSYNCCALL

comexception

I'm building an application in C# that has a static class which initiate a COM class and handles some event handlers of another class that hooks keyboard.
When I call a method of the COM class from a button event handler in my WPF window, the method works without any problems but when I call it in one of the event callbacks within my static class it throws following exception:

Unable to cast COM object of type 'BLAHBLAH' to interface type
'BLAHBLAH'. This operation failed because the QueryInterface call on
the COM component for the interface with IID
'{9DD6680B-3EDC-40DB-A771-E6FE4832E34A}' failed due to the following
error: An outgoing call cannot be made since the application is
dispatching an input-synchronous call. (Exception from HRESULT:
0x8001010D (RPC_E_CANTCALLOUT_ININPUTSYNCCALL)).

Can you please tell me, what this exception means and how can I solve it?

Best Solution

Wrap your code in a new thread:

Thread thread = new Thread(() =>
{
    ManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
    foreach (ManagementObject currentObject in theSearcher.Get())
    {
        Debug.WriteLine("Device present: " + currentObject);          
        ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'");
        serial = theSerialNumberObjectQuery["SerialNumber"].ToString();
    }
});
thread.Start();
thread.Join(); //wait for the thread to finish
Related Question