Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

c# - use the same lock object at two different code block?

Can I use the same lock object at two methods, accessed by two different threads? Goal is to make task1 and task2 thread safe.

object lockObject = new object();

// Thread 1
void Method1()
{
    lock(lockObject)
    {
        // task1
    }
}

// Thread 2
void Method2()
{
    lock(lockObject)
    {
        // task2
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you can use the same lock object (it's technically a monitor in the computer science sense, and is implemented with calls to methods in System.Monitor) in two different methods.

So, say that you had some static resource r, and you wanted two threads to access that resource, but only one thread can use it at a time (this is the classic goal of a lock). Then you would write code like

public class Foo
{
    private static object _LOCK = new object();

    public void Method1()
    {
        lock (_LOCK)
        {
            // Use resource r
        }
    }

    public void Method2()
    {
        lock (_LOCK)
        {
            // Use resource r
        }
    }
}

You need to lock around every use of r in your program, since otherwise two threads can use r at the same time. Furthermore, you must use the same lock, since otherwise again two threads would be able to use r at the same time. So, if you are using r in two different methods, you must use the same lock from both methods.

EDIT: As @diev points out in the comments, if the resource were per-instance on objects of type Foo, we would not make _LOCK static, but would make _LOCK instance-level data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...