I have many threads running in my C# application and each of those threads accesses a TextBox
to log its events. When I set the CheckForIllegalCrossThreadCalls property to false
, I am able to block many cross-threading errors:
System.InvalidOperationException: Cross-thread operation not valid: Control 'myTextBox'
accessed from a thread other than the thread it was created on.
What is the best solution for this problem? Using delegates or disabling CheckForIllegalCrossThreadCalls
as I have tried? Many articles say that disabling CheckForIllegalCrossThreadCalls
is not a good programming practice.
Disabling CheckForIllegalCrossThreadCalls
is like complaining that you get hit by an airbag when crashing your car: the correct solution isn't to remove the airbag, it's to avoid crashing the car.
You simply shouldn't be making UI updates from the wrong thread. You may get away with it most of the time (having disabled the check) but that doesn't mean that it's a good idea - it leaves you open to subtle errors which will only show up occasionally and be really hard to track down.
So yes, use Control.Invoke
, Dispatcher.Invoke
, BackgroundWorker
etc to marshal to the right thread for UI access. That's why those calls/types exist.
An answer to a different question has the answer to you. The short answer is: No. Switch to BackgroundWorkers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.