views:

102

answers:

2

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.

+7  A: 

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.

Hans Passant
+1: I couldn't agree more.
Brian Gideon
+1  A: 

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.

Bob