Reputation: 4232
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.
Upvotes: 2
Views: 397
Reputation: 48959
It depends on what action
is doing with the delegate (formed as a lambda expression your case). If it is executing it synchronously then the second lock
is pointless. Though, it would be safe since a lock
can be reentered. 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. That would be the only the "riff" I can think of.
Upvotes: 0
Reputation: 6109
This will work however, have you looked at the ConcurrentCollections in .NET 4? They are internally threadsafe
Upvotes: 4