Error "The call thread cannot access this object because it belongs to a different thread."

Asked

Viewed 40 times

-2

I have a WPF application that I need to manipulate a textbox. But it gives the following error when running the part of the code that handles the textbox: System.Invalidoperationexception: 'The call thread cannot access this object because it belongs to a different thread. 'The error happens on the line "txt_transcriber.Text = and.Result.Text".

namespace solucao_desktop
{
public partial class TranscriberWindow : Window
{
    public TranscriberWindow()
    {
        InitializeComponent();
    }
    public void transcribrer()
    {
        txt_transcriber.Foreground = Brushes.White;
        var speechConfig = SpeechConfig.FromSubscription("16c50d2a281d4e9cb0834d4ee3a5d9", "brazilsouth");
        speechConfig.SpeechRecognitionLanguage = "pt-BR";
        
        using var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
        using var recognizer = new SpeechRecognizer(speechConfig, audioConfig);
        var stopRecognition = new TaskCompletionSource<int>();

        recognizer.Recognizing += (s, e) =>  //Enquanto estiver captando algum áudio
        {
            txt_transcriber.Text = e.Result.Text;
        };

        recognizer.StartContinuousRecognitionAsync();

        Task.WaitAny(new[] { stopRecognition.Task });
    }
}

2 answers

0

By default the system interface whether Winforms or Wpf runs on a thread itself then access visual elements of another thread started by something like

   Task.Factory.StartNew(() => {Metodo()});

It is simply not possible directly, to perform an interface operation on another thread you need to invoke the action using the Dispatcher responsible for it, an example of implementing this would be to store Dispatcher from the UI thread when starting it for use within your thread in the future, as the example below

using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {

        Dispatcher dispatcher;
        public MainWindow()
        {
            InitializeComponent();

            dispatcher = Dispatcher.CurrentDispatcher;
        }

        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            Task.Factory.StartNew(() =>
           {
               Task.Delay(1000);
               dispatcher.Invoke(() => ChangeColors());
           });
        }

        private void ChangeColors()
        {
            btnTest.Background = Brushes.Red;
            this.Background = Brushes.Blue;

        }
    }
}

-1

I guess that’s how it is:

txt_transcriber.Invoke((Action)(() => txt_transcriber.Text = e.Result.Text);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.