空对象上的 SyncLock
有没有简单的方法来同步锁定可以为空的对象?
在您提出要求之前,是的,我知道对 null 变量执行 SyncLock 是不合逻辑的。但是,这会简化我的代码,因为现在我别无选择,只能在调用 SyncLock 之前对整个地方执行空检查。
If myObjectA Is Nothing Then
myObjectA = myObjectB
Else
SyncLock myObjectA
myObjectA = myObjectB
End SyncLock
End If
Is there simple way to SyncLock an object that can be null?
And before you ask for it, yes, I know that it isn't logical to perform a SyncLock on a null variable. However, that would simplify my code because right now, I have no choice but to perform a null check all over the place before calling a SyncLock.
If myObjectA Is Nothing Then
myObjectA = myObjectB
Else
SyncLock myObjectA
myObjectA = myObjectB
End SyncLock
End If
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,使用 Helper 对象。
当 myObjectA 用作锁时,无论如何您都不应该对其进行分配。
来自 MSDN:
Yes, use a Helper object.
You shouldn't assign to myObjectA anyway when it's used as a Lock.
From MSDN:
不,您不能使用空引用作为锁的标识符。
如果引用可以为空,您甚至不能使用引用作为标识符,因此您当前的代码不是线程安全的。您必须使用不同的方式来识别锁。两个不同的线程可以替换空引用而无法相互排除,这将导致一个引用被另一个引用覆盖:
No, you can't use a null reference as identifier for a lock.
You can't even use a reference as identifier if it can be null, so your current code is not thread safe. You have to use a different way to identify the lock. Two different threads can replace the null reference without being able to exclude each other, which would cause one reference to be overwritten by the other:
可能有一些重构可以帮助避免这些情况。这段代码看起来很奇怪。如果为 null 则将一个对象分配给 lock 变量,如果不是则锁定,这似乎有些错误。另外,您锁定然后更改锁定变量!
请记住,锁定是针对引用而不是值!基本上,它的作用是阻止所有不在锁内的代码块对指定引用的访问。
There is probably some refactoring that would help avoid these situations. This code seems wierd. asigning to the lock variable an object if null and locking if not seems somehow wrong. Plus you lock and then change the lock variable!
Remember that locking goes to the reference not the value! Basically what it does is block acess to the specified reference from all blocks of code not inside the lock.