locking question

  • Thread starter Thread starter Morten Wennevik
  • Start date Start date
M

Morten Wennevik

Hi,

I have a MDIChild with static properties that can be updated at any time
by the MDIParent. These
properties may also at unknown times be accessed by one or more worker
threads.

Now, I'm not too familiar with threads, but is there a danger that these
properties can get corrupted? MDIParent will only SET the properties while
the worker threads will only GET them. If so how do you lock them and to
what?

Morten
 
If you don't use any kind of syncronization, there's a possibility that the
worker threads will read the properties before they've been updated.
Generally speaking, when two or more threads need access to a resource,
access to that resource should be syncronized. All you need to do is lock
on a syncronization object in the get/set of your MDIChild class.
Something like this (note that I used static becasue you mentioned in your
post that your properties are static):

// sync object defined in MDIChild class
private static object syncObject = new object();
...
// the static property of the MDIChild class
private static int theInt = 0;
...
// the static property accessors of MDIChild
public static int MyIntProperty
{
get
{
lock (syncObject)
{
return theInt;
}
}
set
{
lock (syncObject)
{
theInt = value;
}
}
}

Check out this link for more info on multithreaded design:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechar
t/html/vbtchasyncprocvb.asp

hth

-Joel
--------------------
 
Ah,

Thank you, I knew of the possibility of access violations, but the lock
required some object.
Since the properties are static I couldn't use 'this'. So, any object
will do?

Happy coding!
Morten Wennevik [C# MVP]
 
Morten Wennevik said:
Thank you, I knew of the possibility of access violations, but the lock
required some object.
Since the properties are static I couldn't use 'this'. So, any object
will do?

Yes, but preferably (IMO) one which no other classes have access to. I
usually have a separate variable which contains a reference to an
object which is *solely* used for locking. I may have several in a
class, depending on the locking granularity required.

I'm writing a sort of introduction and tips page on multithreading -
I'll post when I'm done with it. (It may be some time though - it's a
nasty subject!)
 
Back
Top