我正在编写一个应用程序来修改另一个应用程序的音量并使用CoreAudioApi
dll 来执行此操作。以下代码块在主线程上完美运行,但在单独的线程中调用时,InvalidCastException
会引发 an。如果这只是两个线程试图访问同一资源的问题,我投入了一个互斥锁,但情况似乎并非如此。关于问题可能是什么的任何想法?作为一个新的 C# 程序员,我很难过。我阅读了其他问题,其中建议只有主线程可以访问 COM 对象,例如 CoreAudioApi,所以我需要向主线程发送某种消息。如果这是正确的,那么最好的方法是什么?
异常(发生在第一个 Math.abs if 语句上):
Unable to cast COM object of type 'System.__ComObject' to interface type 'CoreAudioApi.Interfaces.IMMDevice'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{D666063F-1587-4E43-81F1-B948E807363F}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
代码:
muteSoundMutex.WaitOne();
AudioSessionControl sASC = sInfo.getSAudioSession();
if (Math.Abs(sASC.SimpleAudioVolume.MasterVolume -
(0.05f / defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar)) < 0.0001
&& savedVol > 0)
{
... // other code here. all mutexes are released correctly.