UFO ET IT

C #에 "잠금 시도, 시간 초과시 건너 뛰기"작업이 있습니까?

ufoet 2020. 12. 14. 20:23
반응형

C #에 "잠금 시도, 시간 초과시 건너 뛰기"작업이 있습니까?


객체를 잠그고 이미 잠긴 경우 계속 진행해야합니다 (시간 초과 후 또는 객체없이).

C # 잠금 문이 차단됩니다.


나는 당신이 사용할 수 있다고 믿습니다 Monitor.TryEnter().

lock 문은 Monitor.Enter()호출과 try catch블록으로 변환됩니다 .


Ed는 당신에게 맞는 기능을 가지고 있습니다. 전화하는 것을 잊지 마십시오 Monitor.Exit(). try-finally적절한 정리를 보장 하려면 블록을 사용해야합니다 .

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

동일한 문제가 발생하여 TryLockIDisposable을 구현 하는 클래스 만든 다음 using문을 사용 하여 잠금 범위를 제어했습니다.

public class TryLock : IDisposable
{
    private object locked;

    public bool HasLock { get; private set; }

    public TryLock(object obj)
    {
        if (Monitor.TryEnter(obj))
        {
            HasLock = true;
            locked = obj;
        }
    }

    public void Dispose()
    {
        if (HasLock)
        {
            Monitor.Exit(locked);
            locked = null;
            HasLock = false;
        }
    }
}

그리고 다음 구문을 사용하여 잠급니다.

var obj = new object();

using (var tryLock = new TryLock(obj))
{
    if (tryLock.HasLock)
    {
        Console.WriteLine("Lock acquired..");
    }
}

You'll probably find this out for yourself now that the others have pointed you in the right direction, but TryEnter can also take a timeout parameter.

Jeff Richter's "CLR Via C#" is an excellent book on details of CLR innards if you're getting into more complicated stuff.


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

참고URL : https://stackoverflow.com/questions/8546/is-there-a-try-to-lock-skip-if-timed-out-operation-in-c

반응형