S
S
Sergey Korenevsky2014-12-20 10:24:07
WPF
Sergey Korenevsky, 2014-12-20 10:24:07

How to make TextBox and comport in one thread?

Says that the TextBox is on a different thread than the program itself.
Beleberda, the data is received perfectly and I see them through the console. but refuses to display in textbox,

MainWindow()
{
    var port = new System.IO.Ports.SerialPort("COM2");
    port.DataReceived += (port, e)=>{ AddText(port.ReadExisting().ToString()); };
}

void AddText(string message)
{
    textbox.AppendText(message);//TextBox  --- ERRRRRROR
    // Вызывающий поток не может получить доступ к данному объекту, так как владельцем этого объекта является другой поток.
}

PS WPF, FW 4 Client, VisualStudio 2013 Pro Upd4. W8.1

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sumor, 2014-12-20
@Sumor

You need to switch, if necessary, to the thread that owns the TextBox.
To check, the CheckAccess() function is used. It is not in Intellisence (that is, in auto-add), but it compiles fine.
If you are not in the right thread, then the Invoke function is used to call the code in the right one, from the Dispatcher object of the object in the thread of which you want to execute the code.
The code is something like this (syntax errors are possible - there is no studio at hand):

void AddText(string message)
{
   if (!textbox.CheckAccess())
   {
       textbox.Dispatcher.Invoke(new Action<string>(AddText), message);
   }
   else
   {
       textbox.AppendText(message);
   }   
}

G
GavriKos, 2014-12-20
@GavriKos

You do not believe in those errors which the compiler has shown to you?

B
Boris Benkovsky, 2014-12-20
@benbor

You mean beleberda? This is how wpf works. Some objects (including gui elements) can only be changed in the thread in which they were created. I read this at the university for a long time, the exact mechanism that will help you, I don’t remember
Here is what is in Google stackoverflow.com/questions/11358647/how-to-access...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question