[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 659
  • Last Modified:

Threading and Lock

I have some code which must be thread safe. From past experience with collections I have locked on the SyncRoot property of the object. However, from what I gather, .NET only exposes a SyncRoot property in collections.

I have thought of two approaches which I could use; but I am uncertain as to which is best (or even if there is another better approach).

1. Automatic - have the class, and any derived classes, lock on a protected SyncRoot property every time a thread-safe method is invoked. If this is the best approach, which I feel it may be, is SyncRoot still an appropriate name, or is there another name which is commonly used in .NET? I want to be as consistent as possible.

2. Manual - let client code lock on a public SyncRoot property.

I have tried to lay out these two approaches below:
public class Foo
{
     protected object SyncRoot { get { ... } }
 
     ...
 
     public void Bar()
     {
          lock (SyncRoot)
          {
                ...
          }
     }
}
 
// Thread safe.
Foo test = new Foo();
test.Bar();
 
 
OR
===
 
 
public class Foo
{
     public object SyncRoot { get { ... } }
 
     ...
 
     public void Bar()
     {
           ...
     }
}
 
// Thread safe.
Foo test = new Foo();
lock (test.SyncRoot)
{
     test.Bar();
}

Open in new window

0
numberkruncher
Asked:
numberkruncher
  • 2
1 Solution
 
jorge_torizCommented:
I don't know if this helps but... yes, you are right, use the lock.    I always use it
0
 
numberkruncherAuthor Commented:
I guess the question that I am asking is, should:

a) the class encapsulate this locking on a protected SyncRoot variable.
or
b) I make the SyncRoot variable public and have client-code deal with the locking?

Is there a standard design pattern that .NET uses to do this?

Thanks,
0
 
anarki_jimbelCommented:
Yeah, quite tricky area :)

I don't think it matters if you call the lockobject syncroot or something else. Don't think there are any conventions. Just 'SyncRoot' might be a bit confusing because everybody expects to see it in collections as you pointed out yourself...

I'd prefer the first approach I think... Not sure. May be this article will help:
http://msdn.microsoft.com/en-us/library/3a86s51t(VS.80).aspx
0
 
numberkruncherAuthor Commented:
Thanks for the link, that was quite an interesting read which provides a reassuring example. I am going to go with the first approach but use an alternative name for the lock variable.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now