P
P
Pavel Kityan2015-04-29 15:18:07
.NET
Pavel Kityan, 2015-04-29 15:18:07

Why is there an error accessing the control from another thread?

I’ll make a reservation right away, I don’t create threads manually in the code. But maybe it's the use of a class that manages interaction through SerialPort?
I try to stick to the MVP pattern.
The Presenter is instantiated after the application starts, and pointers are obtained to the created instances of the form classes and the SerialPortManager class, which manages the connection through the COM port.
If the event handler, in which I change controls on forms, hangs on events from the forms themselves, everything is OK.
Or, if you simply refer to the controls in the Presenter (through the setters described in the interfaces that implement the form classes) - that's fine too.
But if the handler in the Presenter is hung up on a custom event that is generated in an object of the SerialPortManager class (and it occurs there after post-processing the SerialPort.DataReceived event), then that's it. Kirdyk.
It turns out that?
1) Is the object working with SerialPort in a separate thread?
2) The handler that climbs to the controls is described in another class (in the Presenter), why are different flows obtained depending on the event source?
I ask without fanaticism, I recently started to deal with C #.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2015-04-29
@bookworm

> The object working with SerialPort is in a separate thread?
Quoting from https://msdn.microsoft.com/en-us/library/system.io... :
The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.
In general, if there is some other logic for processing data coming from the port, then it is better to call it in the DataReceived event, and already in it, after the necessary processing, send higher-level messages to the GUI thread through some kind of message queue, for example organized using ConcurrentQueue . Then your GUI thread will twitch not when a couple of bytes arrive, but when you yourself need it. But this is already an architectural issue, which I advise you to think over if you do not have a one-time lab.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question