简体   繁体   中英

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

I'm writing a plugin (dll file), and I'm creating 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.

您不必创建一个,WinForm应用程序只需创建一个。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM