开发者

Does Speech Recognition using .NET Framework require a message pump?

开发者 https://www.devze.com 2022-12-26 07:15 出处:网络
I\'m writing a plugin (dll file), and I\'m 开发者_StackOverflowcreating a WinForm as its interface/dialog.

I'm writing a plugin (dll file), and I'm 开发者_StackOverflowcreating a WinForm as its interface/dialog. If it does require a message pump, how and where should I create one?


SpeechRecognitionEngine is a wrapper around a apartment-threaded COM server. Yes, a hard requirement for them is at least one thread that is STA and pumps a message loop. Since you are writing a library, you can't control what your client selects. But you can tell her that there's a problem instead of just having your speech recognizer deadlock. Add this check to your class constructor:

  if (System.Threading.Thread.CurrentThread.GetApartmentState() !=
      System.Threading.ApartmentState.STA) {
    throw new InvalidOperationException("UI thread required");
  }

The check is a bit heavy-handed, the recognizer will still work if it is created on a worker thread in a program that also has a UI thread. Although that mode is quite undesirable, every single call to the recognizer will get marshaled and any events you generate will have to be marshaled by the client. I'd suggest an argument to your main class constructor that allows the client to indicate that she really does want the recognizer to run on a thread.


You don't have to create one, the WinForm application has one.


If you are creating a Winforms application in the usual manner, it will create its own message pump. That's all you should need.

0

精彩评论

暂无评论...
验证码 换一张
取 消