반응형
C # 4.0에서 작업을 절전 (또는 지연)하는 방법은 무엇입니까?
.NET 4.5 에는 Task.Delay 가 있습니다.
.NET 4.0에서 어떻게 똑같이 할 수 있습니까?
를 사용하여 4.0 Timer에서 Delay메서드 를 만들 수 있습니다 .
public static Task Delay(double milliseconds)
{
var tcs = new TaskCompletionSource<bool>();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed+=(obj, args) =>
{
tcs.TrySetResult(true);
};
timer.Interval = milliseconds;
timer.AutoReset = false;
timer.Start();
return tcs.Task;
}
NuGet 의 Microsoft.Bcl.Async 패키지를 사용하면 TaskEx.Delay.
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Delay(2000).ContinueWith(_ => Console.WriteLine("Done"));
Console.Read();
}
static Task Delay(int milliseconds)
{
var tcs = new TaskCompletionSource<object>();
new Timer(_ => tcs.SetResult(null)).Change(milliseconds, -1);
return tcs.Task;
}
}
4.0에서 Task.Delay를 구현하는 방법 섹션 에서
다음은 취소 가능한 Task.Delay 구현에 대한 코드 및 샘플 하네스입니다. Delay방법에 관심이있을 것입니다 . :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DelayImplementation
{
class Program
{
static void Main(string[] args)
{
System.Threading.CancellationTokenSource tcs = new System.Threading.CancellationTokenSource();
int id = 1;
Console.WriteLine(string.Format("Starting new delay task {0}. This one will be cancelled.", id));
Task delayTask = Delay(8000, tcs.Token);
HandleTask(delayTask, id);
System.Threading.Thread.Sleep(2000);
tcs.Cancel();
id = 2;
System.Threading.CancellationTokenSource tcs2 = new System.Threading.CancellationTokenSource();
Console.WriteLine(string.Format("Starting delay task {0}. This one will NOT be cancelled.", id));
var delayTask2 = Delay(4000, tcs2.Token);
HandleTask(delayTask2, id);
System.Console.ReadLine();
}
private static void HandleTask(Task delayTask, int id)
{
delayTask.ContinueWith(p => Console.WriteLine(string.Format("Task {0} was cancelled.", id)), TaskContinuationOptions.OnlyOnCanceled);
delayTask.ContinueWith(p => Console.WriteLine(string.Format("Task {0} was completed.", id)), TaskContinuationOptions.OnlyOnRanToCompletion);
}
static Task Delay(int delayTime, System.Threading.CancellationToken token)
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
if (delayTime < 0) throw new ArgumentOutOfRangeException("Delay time cannot be under 0");
System.Threading.Timer timer = null;
timer = new System.Threading.Timer(p =>
{
timer.Dispose(); //stop the timer
tcs.TrySetResult(null); //timer expired, attempt to move task to the completed state.
}, null, delayTime, System.Threading.Timeout.Infinite);
token.Register(() =>
{
timer.Dispose(); //stop the timer
tcs.TrySetCanceled(); //attempt to mode task to canceled state
});
return tcs.Task;
}
}
}
이 답변 에서 아이디어 확장 :
new AutoResetEvent(false).WaitOne(1000);
Visual Studio Async CTP를 다운로드하고 TaskEx를 사용할 수 있습니다.
대부분의 경우 순수한 AutoResetEvent가 Thread.Sleep () ...보다 낫습니다.
AutoResetEvent pause = new AutoResetEvent(false);
Task timeout = Task.Factory.StartNew(()=>{
pause.WaitOne(1000, true);
});
도움이 되길 바랍니다
public static void DelayExecute(double delay, Action actionToExecute)
{
if (actionToExecute != null)
{
var timer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(delay)
};
timer.Tick += (delegate
{
timer.Stop();
actionToExecute();
});
timer.Start();
}
}
Here's a succinct, timer-based implementation with proper cleanup:
var wait = new TaskCompletionSource<bool>();
using (new Timer(_ => wait.SetResult(false), null, delay, Timeout.Infinite))
await wait.Task;
To use this code on .NET 4.0, you need the Microsoft.Bcl.Async NuGet package.
참고URL : https://stackoverflow.com/questions/15341962/how-to-put-a-task-to-sleep-or-delay-in-c-sharp-4-0
반응형
'developer tip' 카테고리의 다른 글
| Redis db에서 모든 키 / 값 쌍 검색 / 나열 (0) | 2020.11.07 |
|---|---|
| 일부 코드를 실행 한 다음 대화 형 노드로 이동 (0) | 2020.11.07 |
| Bash에서 읽기 전용 변수 설정 해제 (0) | 2020.11.07 |
| Java의 enum에서 문자열 값 가져 오기 (0) | 2020.11.07 |
| 헤드리스 인터넷 브라우저? (0) | 2020.11.07 |