Syncronization question

C

Curtis Hatter

Hi,

Hope this question makes sense. =)

I have an object, and a wrapper for that object that implements a
synchronized view (similar to getting a synchronized ArrayList).

What I'm wondering is, if I need to lock all methods? Here's an example:

I have 3 versions of an IndexOf method:

public override void IndexOf(object value) {
return IndexOf(object value, 0)
}

public override void IndexOf(object value, int startIndex) {
return IndexOf(object value, 0, __innerObject.__count);
}

public override void IndexOf(object value, int startIndex, int count) {
lock (__innerObject) {
return (__innerObject.IndexOf(value, startIndex, count);
}
}

is it possible, if i don't lock all the IndexOf methods, that i could get
unexpected results? Or will I be fine since I end up calling a method that
is locked?

Thanks,
Curtis
 
A

Andrew Gnenny

Hi,
It is possible to get unexpected results, because access to
__innerObject.__count instance variable isn't serialized. If another thread
changed value of __innerObject.__count before the first thread redirects the
call to the synchronized method, the count parameter will have invalid
value.
--
Andrew Gnenny
pulsar2003@/no-spam/email.ru (Please remove /no-spam/ for reply)
X-Unity Test Studio
http://x-unity.miik.com.ua/teststudio.aspx
Bring the power of unit testing to VS .NET IDE
 
W

William Stacey

As Andrew said, this is a possible sync issue. To avoid having to lock the
same lock multiple times, have your public methods lock the sync object and
call a new private method with the (object value, int startIndex, int count)
signature. The private method, will not be "locked" but will need to be
called in a locked context (i.e. from one of your public methods.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top