我是新来的,是c#。我正在尝试使用 c# 使用网络上的示例代码通过 Raspberry 进行语音识别。当我从方法调用TextBlock.Text
时,我的程序崩溃。也许是因为这是一个事件处理程序。我该如何解决这个问题?如果我在程序的另一个点(不用作事件处理程序的方法)中使用这三行代码,它可以工作。抱歉,我是新手,我不知道这种语言是如何工作的,如果您可以更正代码,我会更好地理解它。
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!
});
};
}
我相信
您需要调用在其中创建文本框的线程。因此,应将其写为:
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!
});