C#中的锁语句 [英] lock statement in c#

查看:102
本文介绍了C#中的锁语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我上过这样的课:

Ex, i''ve a class like this:

public class myclass
{
      private Object x;
      public void method1()
      {
          lock(x)
          {
                //access to x from thread1
          }
      }
      
      public void method2()
      {
             //access to x from thread2
      }
}



现在,如果从线程调用method1()(但尚未完成).然后从另一个线程调用method2()(method1()尚未从线程thread1完成).线程2是否必须等到method1()完成?



Now, if method1() is called from a thread(but not completed yet). And method2() is called from an another thread(method1() hasn''t completed yet from thread thread1). Will thread2 have to wait until method1() completed?

推荐答案

否,两个方法都必须同时进行锁定.锁定对象可防止其他线程进入该对象的锁定部分.除非锁横跨整个方法主体,否则方法不必整体完成.一旦退出一个锁部分,尝试在同一对象上输入锁的任何其他线程就有机会输入其锁.

No, the locking will have to be in both methods. Locking on an object keeps other threads from entering on a lock section on that object. The method doesn''t have to finish as a whole, unless the lock spans the whole of the method body. As soon as one lock section is exited any other thread trying to enter a lock on the same object get a chance to enter their lock.

public class myclass
{
      private Object x;
      public void method1()
      {
          lock(x)
          {
                //access to x from thread1
          }
      }

      public void method2()
      {
          lock(x)
          {
                //access to x from thread2
          }
      }
}




问候,

-MRB




Regards,

-MRB


不,锁仅在x左右.如果一个线程位于lock块内,而另一个线程试图同时进入锁,则将发生等待.

要使method2成为块,您应该编写如下内容:
No, the lock is only about x. The wait will occure if a thread is inside the lock block, and another thread is trying to enter the lock at the same time.

To make method2 block, you should write something like this:
public void method1()
{
    lock(x)
    {
          //access to x from thread1
    }
}

public void method2()
{
    lock(x)
    {
        ...
    }
}



-------------------------------

但是,我的问题是,如果method2()没有锁语句,它将不得不等待吗?

如果method2中没有锁,它将不会等待.
现在关于是否放置锁,这取决于您在method1method2中执行的操作.
如果将锁放在method1中以保护几个成员,并且访问method2中的相同成员,则可能还必须在method2中使用锁.
如果您做的非常不同,则无需锁定method2.



-------------------------------

But, my question is that if method2() hasn''t got a lock statement, will it have to wait?

If there is no lock in method2, it will not wait.
Now about puting a lock or not, it depends what you do in method1 and method2.
If you put the lock in method1 to protect a few members, and you access the same members in method2, then you will probably have to use a lock in method2 too.
If you do something very different, then you don''t need to lock in method2.


这篇关于C#中的锁语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆