나는 모든,모니터 비동기 제한 시간과 작업 및 취소
내가 취소 해을 수 및 라이브 특정보다 더 시간을 수행하지 않는이 비동기 작업을 모니터링 할 수 있습니다.
나는 다음 코드에 대해 이미 알고있었습니다.
CancellationTokenSource l_cts = new CancellationTokenSource(timemillis);
취소 작업을 수행합니다 (내 비동기 메소드에서 토큰을 모니터링하기 전까지). 그러나이 NOT은 나에게 WHY에 관한 어떤 정보도주지 않았 음, 시간 초과 또는 사용자 취소시겠습니까? 나는 이러한 문제를 해결하기 위해
Token.ThrowIfCancellationRequested();
으로 취소를 잡을하지 않았다 동안 또한, 타임 아웃 이벤트가 지연, 나는 다음과 같은 타임 아웃 프로세스를 썼다.
static async Task TestAsync(int processDelaySeconds, int cancelDelaySeconds, int timeoutDelaySeconds)
{
CancellationTokenSource l_cts = new CancellationTokenSource();
// the process to monitor
Task l_process = new Task((state) =>
{
Console.WriteLine("Process BEGIN");
// dummy loop
for (int l_i = 0; l_i != processDelaySeconds; l_i++)
{
Thread.Sleep(1000);
l_cts.Token.ThrowIfCancellationRequested();
}
Console.WriteLine("Process END");
}, null, l_cts.Token);
// register timeout
RegisteredWaitHandle l_rwh = ThreadPool.RegisterWaitForSingleObject(l_cts.Token.WaitHandle,
(state, timedOut) =>
{
if (timedOut)
{
l_cts.Cancel();
Console.WriteLine("Timed out");
}
else
{
Console.WriteLine("Cancel Signaled");
}
},
null, (int)TimeSpan.FromSeconds(timeoutDelaySeconds).TotalMilliseconds, true);
// cancel task
if (cancelDelaySeconds > 0)
{
Task l_cancel = new Task(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(cancelDelaySeconds));
l_cts.Cancel();
});
l_cancel.Start();
}
try
{
l_process.Start();
await l_process;
}
catch (OperationCanceledException)
{
Console.WriteLine("Task Cancelled");
}
finally
{
// be sure to unregister the wait handle to cancel the timeout
if (l_process.Status != TaskStatus.Canceled) l_rwh.Unregister(l_cts.Token.WaitHandle);
}
Console.WriteLine("Task Status is : {0}", l_process.Status);
}
static async void Tests()
{
Console.WriteLine("NORMAL PROCESS");
Console.WriteLine("--------------");
await TestAsync(2, 10, 10);
Console.WriteLine();
Console.WriteLine("CANCEL");
Console.WriteLine("------");
await TestAsync(5, 2, 10);
Console.WriteLine();
Console.WriteLine("TIMEOUT");
Console.WriteLine("-------");
await TestAsync(10, 15, 2);
}
그럼 내 질문은 : 장면 뒤에 어떤 단점이나 함정이 있습니까? 더 효율적이고 효과적인 방법 ??
ps- 목표는 짧은 코드가 아닌 성능입니다. 당신의 작업이 취소되거나 시간이 초과 된 경우 알하기 위해
실행을 지연 시키려면 Thread.Sleep 대신 Task.Delay를 사용해야합니다. 특히 당신이 공연을 찾고 있다면. – Stilgar
아마 더 적합 : [http://programmers.stackexchange.com/](http://programmers.stackexchange.com/) – Noctis