C# cross-thread operation verification: accessing controls from non-UI threads
When accessing UI elements (such as TextBox) in a thread other than the thread that created the control, you may encounter the exception: "Invalid cross-thread operation: Accessing control 'textBox1' from a thread other than the thread that created it". This is because each UI element is associated with a specific thread for handling events and modifications.
In this example, you are trying to update the serialport1_DataReceived
control from the textBox1
event handler, which executes on a separate thread due to the asynchronous nature of serial port operations.
Solution:
To resolve this issue and safely access the textBox1
control from a non-UI thread, you need to ensure that all interactions with UI elements are called on the main (UI) thread. This can be achieved using a scheduler, which provides a cross-thread communication mechanism and ensures that UI updates are performed on the correct thread.
The following is a modified version of the textBox1
method using the delegated security update serialport1_DataReceived
control:
<code class="language-csharp">private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { // 在UI线程上更新'txt'变量 txt += serialPort1.ReadExisting().ToString(); // 使用委托在UI线程上访问'textBox1'控件 SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { txt.ToString() }); } private delegate void SetTextCallback(string text); private void SetText(string text) { // 检查'textBox1'控件是否在不同的线程上创建 if (this.textBox1.InvokeRequired) { this.Invoke(d, new object[] { text }); } else { // 如果在UI线程上创建,则直接更新'textBox1'控件 this.textBox1.Text = text; } }</code>
With this approach, you ensure that textBox1
controls are always accessed and modified on the main (UI) thread, thus resolving cross-thread operation exceptions.
The above is the detailed content of How to Safely Update UI Controls from Non-UI Threads in C#?. For more information, please follow other related articles on the PHP Chinese website!