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);
}
}
동일한 문제가 발생하여 TryLock
IDisposable을 구현 하는 클래스 를 만든 다음 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
'UFO ET IT' 카테고리의 다른 글
상대 시간에 대한 Javascript 타임 스탬프 (예 : 2 초 전, 1 주 전 등), 최상의 방법? (0) | 2020.12.14 |
---|---|
Vim의 명령 줄 모드에서 일반 모드 모션 사용 (0) | 2020.12.14 |
phpmyadmin이 포함 된 PHP 7은 많은 지원 중단 알림을 제공합니다. (0) | 2020.12.13 |
OSX의 MAMP에서 Apache가 시작되지 않지만 MySQL은 작동합니다. (0) | 2020.12.13 |
YAML에서 코드 블록 재사용 (0) | 2020.12.13 |