views:

54

answers:

3

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?

A: 

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

Robert Harvey
+1  A: 

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

Guffa
+2  A: 

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.

Hans Passant