本文介绍了锁定还会锁定在锁定块内使用的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class ThreadSafe { public static readonly object _locker = new object(); public static int _val1; public int _val2 = 1; public void Go() { lock (_locker) { if (_val2 != 0) Console.WriteLine (_val1 / _val2); _val2 = 0; } } }
在上面的示例中,另一个线程是否可以更改_val2和_val1的值?
In the above example is it possible for another thread to change the values of _val2 and _val1?
推荐答案lock关键字仅锁定对代码段的访问,而不能锁定对代码段的访问内部使用的数据.这意味着即使执行了锁定部分,另一个线程也可能同时修改_val1和_val2. 希望这会有所帮助, 弗雷德里克(Fredrik) The lock keyword locks only access to the code section, not the data used inside of it. This means that it is possible for another thread to modify both _val1 and _val2 even when the locked section is executed. Hope this helps, Fredrik
更多推荐
锁定还会锁定在锁定块内使用的变量吗?
发布评论