Class and Multi-thread safety

  • Thread starter Thread starter Nuno Magalhaes
  • Start date Start date
N

Nuno Magalhaes

Hello,

Is there any keyword applicable to a class to make it thread-safe?
Without having to put lock(this){} in all functions?

Thanks.
 
Nuno Magalhaes said:
Is there any keyword applicable to a class to make it thread-safe?
Without having to put lock(this){} in all functions?

Putting lock(this) doesn't make it thread-safe.

Thread safety is not a simple matter - you need to carefully consider
threading and various issues when making a class thread-safe. In
particular, think about any code in other classes you call while
holding a lock - if you're not careful, you can easily deadlock.

I'd also recommend against locking on "this" to start with.
 
Putting lock(this) doesn't make it thread-safe.

Thread safety is not a simple matter - you need to carefully consider
threading and various issues when making a class thread-safe. In
particular, think about any code in other classes you call while
holding a lock - if you're not careful, you can easily deadlock.

I'd also recommend against locking on "this" to start with.

What is the difference between locking on "this" and locking on an
object inside the class? My object is never changed. What can go wrong?
 
Nuno Magalhaes said:
What is the difference between locking on "this" and locking on an
object inside the class? My object is never changed. What can go wrong?

Someone else can acquire a lock on it, inadvertently blocking things at
the wrong time. The more control you can exercise over what lock is
taken out when, the fewer deadlock risks you'll have.
 
Nuno said:
What is the difference between locking on "this" and locking on an
object inside the class? My object is never changed. What can go wrong?

lock(this) is not considered good practice (anymore). Check MS docs for the
lock statement for more information.

Regards,

Mads

--
Med venlig hilsen/Regards

Systemudvikler/Systemsdeveloper cand.scient.dat, Ph.d., Mads Bondo
Dydensborg
Dansk BiblioteksCenter A/S, Tempovej 7-11, 2750 Ballerup, Tlf. +45 44 86 77
34
 

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

Back
Top