現象:保留 [STAThread] 時調用 SRE.SetInputToDefaultAudioDevice() 拋出異常;去掉則語音正常但其他窗體異常。
System.Speech 底層調用 SAPI COM 組件,要求 MTA(多線程單元) 模式。[STAThread] 強制主線程進入 STA(單線程單元),導致 COM 組件初始化失敗。[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// 啟動語音線程(MTA)
Thread speechThread = new Thread(() => {
// 必須在 MTA 線程中創建 SpeechRecognitionEngine
var sre = new SpeechRecognitionEngine();
sre.SetInputToDefaultAudioDevice();
// ... 加載語法、註冊事件、RecognizeAsync
});
speechThread.SetApartmentState(ApartmentState.MTA); // 關鍵!
speechThread.IsBackground = true;
speechThread.Start();
Application.Run(new MainForm()); // 主線程保持 STA
}
Control.Invoke 或 SynchronizationContext。sre.Dispose()。Microsoft.CognitiveServices.Speech (NuGet) 避免 COM 依賴。