This blog is subject the DISCLAIMER below.

Sunday, July 22, 2007

Threading 2

If you don’t know about threading please go and read the first part

In this part we will talk about some light part in threading and a special part for GUI programming, if you work with controls which created by the main thread of your application and want to access them by another thread, if you did, you would get this error “System.InvalidOperationException was unhandled
Message="Cross-thread operation not valid: Control 'Your Control' accessed from a thread other than the thread it was created on.”

This is in debug mode and you can disable this exception by writing this line CheckForIllegalCrossThreadCalls = false;

What I’ve found out that’s .NET don’t treat with Form as a control, in the previous post you cannot get this exception although you access the form from a thread which not the one created by.

Anyway, more than one thread on one the same data == inconsistency, race condition, deadlock lmlmlaa, and you MUST keep that in your mind while working with more than one thread on shared data and try to solve these issues.

You should maintain the consistency yourself but also working by volatile keyword isn’t the good way as MSDN says:
Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread.

To read more about volatile keyword see this

.NET team created a special component to solve and control this issue (doing some operation on a control created in a different thread) and this is called BackgroundWorker, let’s see how it works.

Drag from VS toolbox ->Components tab ->BackgroundWorker and drop it on your target form.
We almost done :)
Double click on BackgroundWorker to create its default event handler DoWork and call Start method which changes the Text of form to a number each 100 millisecond.

Sample code

No comments: