FCI-Helwan blog

Just another FCI-H weblog

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

Advertisements

July 22, 2007 - Posted by | C#

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: