3

I have question regarding threading in c#.See the code posted below.

 public class TestThreading
{
    private System.Object lockThis = new System.Object();

    public void Function1()
    {

        lock (lockThis)
        {
            // Access thread-sensitive resources.
        }
    }

    public void Function2(){
        lock (lockThis)
        {
            // Access thread-sensitive resources.
        }

    }

}

Now my question is if some thread entered in Function1 (inside lock block) and at the same time another thread enters in Function2 what will happen

  1. The threads will execute independently.
  2. The thread which entered in Function 2 Goes to waits until lock is released by Funtion1 thread.
  3. The thread which entered in Function 2 throws exception.

I am new to c# hence asking simple basic question. Thanks in advance.

4

3 回答 3

3

在 Function 2 中进入的线程 Goes to 等待,直到 Function1 线程释放锁。

锁的目的只是:提供一个“安全”的代码区域,一次只能由一个线程访问。另一个线程将进入睡眠状态,并在第一个线程释放锁时恢复。

于 2013-05-29T10:16:09.303 回答
1

2号会发生。第二个线程在执行之前将等待锁被释放。

于 2013-05-29T10:16:20.553 回答
1

第二个线程将等待第一个线程释放锁,然后它才会获取锁并执行您的代码

我建议阅读以下描述多线程问题和库的文章

托管线程最佳实践

C#中的线程约瑟夫·阿尔巴哈里

于 2013-05-29T10:16:21.880 回答