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

前端 未结 5 1576
执念已碎
执念已碎 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:47

    Consider using AutoResetEvent and its method WaitOne with a timeout input.

    static AutoResetEvent autoEvent = new AutoResetEvent(true);
    if(autoEvent.WaitOne(0))
    {
        //start critical section
        Console.WriteLine("no other thread here, do your job");
        Thread.Sleep(5000);
        //end critical section
        autoEvent.Set();
    }
    else
    {
        Console.WriteLine("A thread working already at this time.");
    }
    

    See https://msdn.microsoft.com/en-us/library/cc189907(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.threading.autoresetevent(v=vs.110).aspx and https://msdn.microsoft.com/en-us/library/cc190477(v=vs.110).aspx

提交回复
热议问题