简体   繁体   中英

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? They are internally threadsafe

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM