本文介绍了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?

推荐答案

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


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#中的锁语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 20:31