Reputation: 6524
I have a method that is getting called from multiple threads. Each of the threads have their own instance of the class. What's the most straightforward way to synchronize access to the code?
I can't just use lock(obj)
where obj
is an instance member, but would it be sufficient to just declare obj
as static on the class? So all calls to the method would be locking on the same object? A simple illustration follows:
class Foo
{
static object locker = new object();
public void Method()
{
lock(locker)
{
//do work
}
}
}
EDIT: The //do work
bit is writing to a database. Why I need to serialize the writes would take 3 pages to explain in this particular instance, and I really don't want to relive all the specifics that lead me to this point. All I'm trying to do is make sure that each record has finished writing before writing the next one.
Upvotes: 0
Views: 2213
Reputation: 273244
You left out the most important part: what data is involved in // do work
If // do work
uses static data then you have the right solution.
If // do work
only uses instance data then you can leave out the lock() {}
altogether (because 1 instance belongs to 1 Thread) or use a non-static locker
(1 instance, multiple threads).
Upvotes: 1
Reputation: 3351
Your example would certainly work, though there must be some resource that is being shared across the different instances of the class to make that necessary.
Upvotes: 1
Reputation: 941455
Why do you need any synchronization when the threads each have their own instance? Protect the resource that is shared, don't bother with unshared state. That automatically helps you find the best place for the locking object. If it is a static member that the objects have in common then you indeed need a static locking object as well.
Upvotes: 8