Handling the "Cross-thread Operation Not Valid" Exception in C# Multithreaded Applications
In C# applications employing multiple threads, it's vital to ensure that UI elements are accessed exclusively by the thread responsible for their creation. Violating this principle leads to the dreaded "Cross-thread operation not valid" exception.
Understanding C# Threading and UI Element Ownership
C# allows concurrent execution through multiple threads. Each thread operates independently within its own context. Crucially, UI elements (like text boxes) belong to a specific thread, typically the main UI thread.
The Problem: Accessing UI Elements from Unauthorized Threads
The error arises when a thread other than the owning thread attempts to modify a UI element's properties. This is a common scenario, often encountered when handling events from background threads (like serial port data reception).
The Solution: Implementing Dispatcher Invocation
The solution involves using a dispatcher to marshal operations onto the correct thread. This guarantees thread-safe modifications of UI controls.
Code Implementation
Here's how to implement this solution:
First, define a delegate:
<code class="language-csharp">private delegate void SetTextCallback(string text);</code>
Next, create a method to safely update the text box:
<code class="language-csharp">private void SetText(string text) { if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } }</code>
Finally, within your serial port data received event handler, call the SetText
method:
<code class="language-csharp">private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { txt += serialPort1.ReadExisting(); SetText(txt); }</code>
This approach ensures that the textBox1.Text
property is updated safely, preventing the "Cross-thread operation not valid" exception. The InvokeRequired
check efficiently determines whether a dispatcher call is necessary.
The above is the detailed content of How to Solve the 'Cross-thread Operation Not Valid' Error in C# Multithreading?. For more information, please follow other related articles on the PHP Chinese website!