懒惰ExecutionAndPublication - 可能导致死锁的示例
LazyThreadSafetyMode 的文档指出,使用值 ExecutionAndPublication 可以如果初始化方法(或默认构造函数,如果没有初始化方法)内部使用锁,则会导致死锁。我试图更好地理解使用此值时可能导致死锁的示例。在使用此值时,我正在初始化 ChannelFactory。我看不到 ChannelFactory 的构造函数使用任何内部锁(使用 Reflector 查看类),所以我相信这种情况不适合可能的死锁情况,但我很好奇什么情况可能导致死锁以及是否可能存在死锁初始化 ChannelFactory 时发生死锁。
因此,总而言之,我的问题是:
使用 ExecutionAndPublication 初始化 ChannelFactory 是否可能导致死锁?
有哪些可能的方法会导致使用 ExecutionAndPublication 初始化其他对象时出现死锁?
假设您有以下代码:
class x
{
static Lazy<ChannelFactory<ISomeChannel>> lcf =
new Lazy<ChannelFactory<ISomeChannel>>(
() => new ChannelFactory<ISomeChannel>("someEndPointConfig"),
LazyThreadSafetyMode.ExecutionAndPublication
);
public static ISomeChannel Create()
{
return lcf.Value.CreateChannel();
}
}
The documentation for LazyThreadSafetyMode states that using the value ExecutionAndPublication could cause deadlocks if the initialization method (or the default constructor, if there is no initialization method) uses locks internally. I am trying to get a better understanding of examples that could cause a deadlock when using this value. In my use of this value, I am initializing a ChannelFactory. I cannot see the ChannelFactory's constructor using any internal locks (reviewing the class with Reflector), so I believe this scenario does not fit the possible deadlock situation, but I am curious what situations could cause a deadlock as well as if there could be a possible deadlock initializing the ChannelFactory.
So, to summarize, my questions are:
Is it possible to cause a deadlock initializing the ChannelFactory using ExecutionAndPublication?
What are some possible ways to cause a deadlock initializing other objects using ExecutionAndPublication?
Suppose you have the following code:
class x
{
static Lazy<ChannelFactory<ISomeChannel>> lcf =
new Lazy<ChannelFactory<ISomeChannel>>(
() => new ChannelFactory<ISomeChannel>("someEndPointConfig"),
LazyThreadSafetyMode.ExecutionAndPublication
);
public static ISomeChannel Create()
{
return lcf.Value.CreateChannel();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Init()
从数据库读取,因此它必须使用锁。UpdateDb()
写入数据库,因此它也需要锁,并且由于Lazy
在这种情况下内部也使用锁,因此会导致死锁。在这种情况下,通过将
UpdateDb()
中对lazyInt.Value
的访问移到 lock 语句之外,可以很容易地修复死锁,但这可能不是那么简单(或明显)在其他情况下。Init()
reads from the DB, so it has to use the lock.UpdateDb()
writes to the DB, so it needs the lock too, and sinceLazy
uses a lock internally too in this case, it causes deadlock.In this case, it would be easy to fix the deadlock by moving the access to
lazyInt.Value
inUpdateDb()
outside the lock statement, but it may not be so trivial (or obvious) in other cases.