In addition to Solution 1.
There is one specific problem when you use speech recognition which applies to any thread, even if this is the starting thread of your application: apartment states. Recognizers have a serious limitation: each of one can work only in one thread, and this thread should be of one certain apartment state. Also, I did not found this in documentation, it can only be found from exceptions related to this problem.
So,
System.Speech.Recognition.SpeechRecognizer
requires STA thread, and
System.Speech.Recognition.SpeechRecognitionEngine
MTA. Please see (this requirement is
not documented:
http://msdn.microsoft.com/en-us/library/system.speech.recognition.speechrecognizer%28v=vs.110%29.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.speech.recognition.speechrecognitionengine%28v=vs.110%29.aspx[
^].
Now, this is one of the several reasons why a separate thread could be important (and, unlike other reasons, this one is absolutely critical). For example, WPF application can only use
STAThread
. To use
System.Speech.Recognition.SpeechRecognitionEngine
, you always need to use MTAThread in a different thread. This is how:
http://msdn.microsoft.com/en-us/library/system.threading.thread.getapartmentstate%28v=vs.110%29.aspx[
^].
Note that you cannot call
Thread.SetApartmentState
from the same thread. It can be done by the thread uses to start the thread, and only before starting it.
Now, both console-only applications can work in both
MTAThread
and
STAThread
. Same goes about
System.Windows.Forms
. If you want to execute one the recognizers on respective main threads of the application, you need to make sure you have correct
attribute applied to the entry-point method of the application, for example:
using System;
[STAThread]
static void Main(string[] args) { }
or
[MTAThread]
static void Main(string[] args) { }
—SA