blabla blabla - 1 year ago 81
C# Question

Is disabling 'CheckForIllegalCrossThreadCalls' a good way of blocking cross-threading errors?

I have many threads running in my C# application and each of those threads accesses a

to log its events. When I set the CheckForIllegalCrossThreadCalls property to
, 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
as I have tried? Many articles say that disabling
is not a good programming practice.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download