Is there a “try to lock, skip if timed out” operation in C#?

前端 未结 5 1571
执念已碎
执念已碎 2020-12-23 11:17

I need to try to lock on an object, and if its already locked just continue (after time out, or without it).

The C# lock statement is blocking.

5条回答
  •  爱一瞬间的悲伤
    2020-12-23 11:51

    Ed's got the right function for you. Just don't forget to call Monitor.Exit(). You should use a try-finally block to guarantee proper cleanup.

    if (Monitor.TryEnter(someObject))
    {
        try
        {
            // use object
        }
        finally
        {
            Monitor.Exit(someObject);
        }
    }
    

提交回复
热议问题