473,728 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Lock and Synchronized

Some classes, like Queue and SortedList, have a Synchronized method which gives a thread safe wrapper object for these classes. But the lock() statement does the same thing. Is there any rules as to when to use one and not the other? For instance, if I wanted to remove an item in a SortedList, would it be better to lock() it or do it via the Synchronized wrapper? Why choose one over the other

SortedList sl

lock(sl

sl.Remove(item)
O

SortedList sl2 = SortedList.Sync hronized(sl)
sl2.Remove(item )

Same question for iterations. Does lock() and synchronized do the same thing

lock(sl

for(int i = 0; i < sl.Count; i++


O

SortedList sl2 = SortedList.Sync hronized(sl)
for(int i = 0; i < sl2.Count; i++

Thanks

Rich Sienkiewic
Dictaphone Corp
Jul 21 '05 #1
4 8055
Synchronized? IsSynchronized is a property that returns a bool. It doesn't
return "a synchronized object". You're thinking of SyncRoot, maybe?

But anyway, the correct way is to lock on the SyncRoot object returned by
the hash/list class. Locking on the type instance itself is not recommended
and is actually unsafe.

--
_______________ _____
Klaus H. Probst, MVP
http://www.vbbox.com/

"Rich Sienkiewicz" <an*******@disc ussions.microso ft.com> wrote in message
news:CD******** *************** ***********@mic rosoft.com...
Some classes, like Queue and SortedList, have a Synchronized method which gives a thread safe wrapper object for these classes. But the lock()
statement does the same thing. Is there any rules as to when to use one and
not the other? For instance, if I wanted to remove an item in a SortedList,
would it be better to lock() it or do it via the Synchronized wrapper? Why
choose one over the other.
SortedList sl;

lock(sl)
{
sl.Remove(item) ;
}

OR

SortedList sl2 = SortedList.Sync hronized(sl);
sl2.Remove(item );
Same question for iterations. Does lock() and synchronized do the same thing?
lock(sl)
{
for(int i = 0; i < sl.Count; i++)
{
}
}

OR

SortedList sl2 = SortedList.Sync hronized(sl);
for(int i = 0; i < sl2.Count; i++)
{
}
Thanks,

Rich Sienkiewicz
Dictaphone Corp

Jul 21 '05 #2
Klaus H. Probst <us*******@vbbo x.com> wrote:
Synchronized? IsSynchronized is a property that returns a bool. It doesn't
return "a synchronized object". You're thinking of SyncRoot, maybe?
No, he's thinking of Synchronized, rather than IsSynchronized.
SortedList.Sync hronized, however, is a method which returns a
synchronized wrapped for the SortedList.
But anyway, the correct way is to lock on the SyncRoot object returned by
the hash/list class. Locking on the type instance itself is not recommended
and is actually unsafe.


The latter is certainly true. The former is "sort-of" true.

The synchronized wrapper make each call to the list synchronized.
However, most of the time that isn't actually enough - you typically
want to synchronize a *sequence* of operations rather than one
operation at a time.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #3
Thanks for the reply guys. But I'm more confused. I should not lock the instance like this

lock(sl

but lock the SyncRoot, like this

lock(sl.SyncRoo t

But the help system (C# Programmer's Reference) describing the lock statement says "The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock." It never mentions the SyncRoot, just lock the instance itself.

The help system is misleading then in talking about the Synchronized method. It says, for the SortedList.Sync hronized method, "Returns a synchronized (thread-safe) wrapper for the SortedList.". Then in the Remarks section it says "To guarantee the thread safety of the SortedList, all operations must be done through this wrapper only." That to me says get and use the wrapper for thread safety. If this is not true then this must be reworded, no

So my question remains, if I have one thread iterating over a SortedList and another thread can come along and add/delete an item from it, what should each thread do to the SortedList, lock or Synchronize

Thanks

Rich
Jul 21 '05 #4
Locking the object is fine.

If you were thinking of using:

lock(this)

You should know that because you're looking on your instance, users of your
class could also lock on it and screw you up. Whether or not that is an
issue depends on what you think your users might do. The same situation
exists if you're doing:

lock(typeof(MyC lass))

If you don't want to do this, you can easily allocate a static or instance
object (ie object myLock = new object()), and then lock on that.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://weblogs.asp.net/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
"Rich Sienkiewicz" <an*******@disc ussions.microso ft.com> wrote in message
news:E6******** *************** ***********@mic rosoft.com...
Thanks for the reply guys. But I'm more confused. I should not lock the instance like this:
lock(sl)

but lock the SyncRoot, like this?

lock(sl.SyncRoo t)

But the help system (C# Programmer's Reference) describing the lock statement says "The lock keyword marks a statement block as a critical
section by obtaining the mutual-exclusion lock for a given object, executing
a statement, and then releasing the lock." It never mentions the SyncRoot,
just lock the instance itself.
The help system is misleading then in talking about the Synchronized method. It says, for the SortedList.Sync hronized method, "Returns a
synchronized (thread-safe) wrapper for the SortedList.". Then in the Remarks
section it says "To guarantee the thread safety of the SortedList, all
operations must be done through this wrapper only." That to me says get and
use the wrapper for thread safety. If this is not true then this must be
reworded, no?
So my question remains, if I have one thread iterating over a SortedList and another thread can come along and add/delete an item from it, what
should each thread do to the SortedList, lock or Synchronize?
Thanks,

Rich

Jul 21 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
10692
by: memememe | last post by:
in java if I was calling a synchronized block and wanted to sync it even for static blocks of code I could do a synchronize(theObject.getClass()), can I do a lock(theObject.GetType()) on C# and will it lock for static blocks of code that use that object type?
5
29618
by: Seeker | last post by:
Hello, I've read conflicting posts about . Does it or does it not lock the entire object? In my simple test it appears to block just the method but I wouldn't exactly call my meager test conclusive... thanks, Scott
14
6323
by: Sharon | last post by:
Hi all. I have an ArrayList and sometimes while enumerating through, i get an exception because another thread has added to the ArrayList. To solve this problem, i lock the enumeration, passing the ArrayList instance to the lock. But i still get the same exception. Thanks for your help. Sharon.
2
13203
by: Shawn B. | last post by:
Greetings, What is the difference between lock(...) and Monitor.Enter(...) / Monitor.Exit(...) ? Thanks, Shawn
5
4908
by: norbert.thek | last post by:
Hi Can somebody tell me if I'm right or not The attribute Is like an lock(this) over the Method where i put this Attribute?! If I have two methods like:
4
348
by: Rich Sienkiewicz | last post by:
Some classes, like Queue and SortedList, have a Synchronized method which gives a thread safe wrapper object for these classes. But the lock() statement does the same thing. Is there any rules as to when to use one and not the other? For instance, if I wanted to remove an item in a SortedList, would it be better to lock() it or do it via the Synchronized wrapper? Why choose one over the other SortedList sl lock(sl sl.Remove(item) O
2
3560
by: yaron | last post by:
Hi, Does MethodImpl Synchronized attribute is like lock(this) ? i mean that a call to Monitor.PulseAll(this) from a Synchronized method will trigger other thread that call to Monitor.Wait(this) ? Thanks.
3
2981
by: Ryan Liu | last post by:
Hi, What does ArrayList.Synchronized really do for an ArrayList? Is that equal to add lock(this) for all its public methods and properties? Not just for Add()/Insert()/Remvoe()/Count, but also for Item (this)? Normally,do I need sync at all? Isn't that true without sync the program can run faster?
94
30333
by: Samuel R. Neff | last post by:
When is it appropriate to use "volatile" keyword? The docs simply state: " The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock Statement (C# Reference) statement to serialize access. " But when is it better to use "volatile" instead of "lock" ?
0
8760
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9280
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9139
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8140
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2673
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.