2016-02-26 145 views
0

我是新來的,並與C#。我試圖使用C#語音識別與樹莓使用網上找到的示例代碼。當我從方法調用TextBlock.Text時,我的程序崩潰。也許是因爲這是一個事件處理程序。我該如何解決這個問題? 如果我在程序的另一點(方法不用作事件處理程序)中使用這三行代碼,它將起作用。 對不起,但我是新來的,我不知道這種語言是如何工作的,如果你能糾正我的代碼,我會更好地理解它。事件處理程序C#和TextBlock

namespace RPiVoice 
{ 

    public sealed partial class MainPage : Page 
    { 
     private const int RED_LED_PIN = 5; 
     ... 

     public MainPage() 
     { 
      this.InitializeComponent(); 
      Unloaded += MainPage_Unload 
      initializeSpeechRecognizer(); 
      initializeGPIO(); 
     } 

     private void initializeGPIO() 
     { 
         gpio = GpioController.GetDefault(); 

      // // Initialize GPIO Pins 
      redPin = gpio.OpenPin(RED_LED_PIN); 
      greenPin = gpio.OpenPin(GREEN_LED_PIN); 
      bedroomLightPin = gpio.OpenPin(BEDROOM_LIGHT_PIN); 

      redPin.SetDriveMode(GpioPinDriveMode.Output); 
      greenPin.SetDriveMode(GpioPinDriveMode.Output); 
      bedroomLightPin.SetDriveMode(GpioPinDriveMode.Output); 

      // Write low initially, this step is not needed 
      redPin.Write(GpioPinValue.Low); 
      greenPin.Write(GpioPinValue.Low); 
      bedroomLightPin.Write(GpioPinValue.Low); 
     } 
     // Initialize Speech Recognizer and start async recognition 
     private async void initializeSpeechRecognizer() 
     { 

      // Initialize recognizer 
      var recognizer = new SpeechRecognizer(new Windows.Globalization.Language("it-IT")); 

      // Set event handlers -> the problem should be here 
      recognizer.StateChanged += RecognizerStateChanged; 
      recognizer.ContinuousRecognitionSession.ResultGenerated += RecognizerResultGenerated; 

     } 

     // Recognizer generated results 
     private async void RecognizerResultGenerated(SpeechContinuousRecognitionSession session, SpeechContinuousRecognitionResultGeneratedEventArgs args) 
     { 
      ... 


        await Window.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { 
         this.Stato.Text = "test"; //this make the program crash! 
        }); 

       }; 
} 
+0

你得到的例外,你可以告訴我們嗎? – Gabe

回答

0

我相信你需要調用線程文本框在創建因此,它應該寫成:

this.Dispatcher.Invoke((Action)(() => 
{ 
     this.Stato.Text = "test"; 
})); 

不是:

   await Window.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { 
        this.Stato.Text = "test"; //this make the program crash! 
       });