Threading: Stopping Errors

vbguru

New member
Joined
Jan 22, 2009
Messages
2
Programming Experience
5-10
Ok guys... so how bad is using:
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False

In my app, the only reason I am doing threading is because it will take long to process and I want the UI to stop locking up.

In my threading process when everything is completed, if I turn on or off a control it was crashing saying it was cross threading.

I am not concerned if that control is being used by another process.It wont be a problem. So what is the reason I shoul shy away from the above code.
 
Accessing a control from a different thread than it was created on is wrong, it is a programming error, and you see the application stops with an exception if you do this. CheckForIllegalCrossThreadCalls was introduced in .Net 2.0 as a way to helps programmers identify such errors during debugging. That you can turn off this notification, and that something doesn't actually go wrong, doesn't mean you still have made an error in programming. So remove that instruction again and learn how to deal with the problem. The solution is using Control.Invoke, and it is easy. Using a Backgroundworker can save you from learning what a delegate is, using its Progress/Complete events you can safely access UI. BGW is an easy to handle threading component that has many uses, not only for beginners that don't know how to call Control.Invoke.

Now, that you're here I can quickly explain Control.Invoke. It is used to call a delegate that points to the method you wanted to call directly. Instead the Invoke functionality runs the method on the Controls thread, which is safe. Let's say you're in a thread and want to call a method UpdateUI that sets Text for some Labels.
VB.NET:
Me.Label1.Invoke(New MethodInvoker(AddressOf UpdateUI))
MethodInvoker is here a standard .Net delegate, it is defined in .Net library like this:
VB.NET:
Delegate Sub MethodInvoker()
As you see the code creates a new instance of the MethodInvoker delegate and points it to the UpdateUI method, and the Label1 control invokes this delegate instance. The thread-safe result is achieved, the UpdateUI method is executed on the thread that the Label belongs to.

.Net has several predefined delegates that you can or will use in some situations, but nothing stops you from defining a delegate yourself as above, as a function or sub method that takes the parameters you specify.
 
Thanks

Thanks for your assistance. I saw a few things online about my error, but your explanation made a lot of sense.
 
Back
Top