[英]Using of anonymous methods in lock statement
I have to organize thread safe removing of items from collection, with using anonymous method.我必须使用匿名方法组织线程安全地从集合中删除项目。 Something like this.
像这样的东西。
...
lock(this.set)
{
...
this.set.Add(item);
action(()=>{
lock(this.set)
{
this.set.Remove(item);
}
});
}
...
Anonymous method will be executed by the time, probably, from another thread.匿名方法将在那时被执行,可能是从另一个线程执行的。 Is this way of lock operators correct?
这种锁定操作员的方式是否正确? Is there are some riffs i have to take into account here?
这里有一些我必须考虑的即兴演奏吗?
Thanks in advance.提前致谢。
This will work however, have you looked at the ConcurrentCollections in .NET 4?但是,这将起作用,您是否查看过 .NET 4 中的 ConcurrentCollections? They are internally threadsafe
它们是内部线程安全的
It depends on what action
is doing with the delegate (formed as a lambda expression your case).这取决于对委托执行的
action
(在您的情况下形成为 lambda 表达式)。 If it is executing it synchronously then the second lock
is pointless.如果它是同步执行的,那么第二个
lock
是没有意义的。 Though, it would be safe since a lock
can be reentered.不过,这将是安全的,因为可以重新进入
lock
。 If it is executing it asynchronously on another thread then you could deadlock both threads if action
waits for any invocation of the delegate to complete.如果它在另一个线程上异步执行它,那么如果
action
等待委托的任何调用完成,您可能会死锁两个线程。 That would be the only the "riff" I can think of.那将是我能想到的唯一“即兴演奏”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.