回答
可以使用Timer
創建Delay
方法在4.0:
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;
}
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;
}
}
您也可以下載Visual Studio Async CTP和使用TaskEx.Delay
這不是一個好主意,CTP包含了永遠不會修復的已知錯誤。使用Bcl.Async是一個更好的選擇。 – svick 2013-11-15 12:20:48
使用來自NuGet的Microsoft.Bcl.Async包裝,它有TaskEx.Delay
。
重要的信息是類名是* TaskEx *而不是*任務*! – OneWorld 2017-07-24 12:42:33
以下是可取消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;
}
}
}
看起來不太好!如果我用同樣的CancellationToken調用很多延遲,我會得到很多代表在代碼上註冊。 – RollingStone 2017-06-09 13:01:33
在很多情況下,一個純粹的AutoResetEvent比Thread.sleep()方法可能會更好...感興趣
AutoResetEvent pause = new AutoResetEvent(false);
Task timeout = Task.Factory.StartNew(()=>{
pause.WaitOne(1000, true);
});
希望它有助於
我認爲最初的想法是阻止當前線程,而不是在另一個線程上等待,稍後在當前線程中通知。那麼,[this](https://stackoverflow.com/a/46087483/4955344)呢? – 2017-09-07 03:49:49
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();
}
}
這裏有一個簡潔的,基於定時器的實現與適當的清理:
var wait = new TaskCompletionSource<bool>();
using (new Timer(_ => wait.SetResult(false), null, delay, Timeout.Infinite))
await wait.Task;
要在.NET 4.0上使用此代碼,您需要使用Microsoft.Bcl.Async NuGet包。
OP要求約4.0 - 4.0中沒有「等待」。 – 2017-09-07 03:28:32
'await'關鍵字是C#語言的一部分,它與.NET Framework版本是分開的。問題在於'任務
如果一個使用[Microsoft.Bcl.Async](https://www.nuget.org/packages/Microsoft.Bcl.Async/),是不是'TaskEx.Delay'更接受,那麼? – 2017-09-08 22:36:54
從這個answer擴展思路:
new AutoResetEvent(false).WaitOne(1000);
- 1. 機器人,有沒有任何方法讓服務延遲或睡眠?
- 2. 取消.Net 4.0中的任務延遲
- 3. jquery:如何睡覺或延遲?
- 4. 睡眠()延遲輸出,直到結束
- 5. Curl:請求之間的睡眠/延遲
- 6. 使用Adobe Air延遲或睡眠程序一段時間
- 7. 設置沒有睡眠的延遲objective-c
- 8. 延遲後執行C++函數而不使用睡眠
- 9. 如何在c#4.0中實現任務延續
- 10. 如何使用睡眠延遲PHP電子郵件
- 11. 如何在Windows中的Silverlight應用程序,而不是使用線程睡眠任務延遲
- 12. 在延遲工作中設置睡眠時間
- 13. 在Win 32上如何讓程序在C++中睡眠?
- 14. 新手:又一個非阻塞延遲:沒有睡眠延遲LED開啓()
- 15. 如何在Linux上如何睡眠或暫停c中的PThread
- 16. Swift中的延遲/睡眠不起作用
- 17. Python中的準確睡眠/延遲while循環
- 18. 如何使用Celery延遲任務?
- 19. GAE任務隊列如何使延遲?
- 20. Bukkit延遲任務在For Loop中
- 21. 如何修復目標C sdk 4.0上的睡眠?
- 22. 睡眠()或睡眠()的準確程度
- 23. 休眠延遲寫
- 24. 如何讓Maven執行睡眠
- 25. cakephp簡單測試webtester延遲/睡眠功能
- 26. Windows睡眠微秒用於低延遲線程通信
- 27. 用於ASP.NET的非鎖定睡眠/ waitfor /延遲功能
- 28. 使用睡眠命令延遲一個月
- 29. 如何在電話睡眠後保持任務存活?
- 30. 如何禁用睡眠/睡眠功能?
[Thread.sleep代碼(http://msdn.microsoft.com/en-us/library/system.threading.thread.sleep.aspx)? – Default 2013-03-11 15:07:46
看看這裏:http://msdn.microsoft.com/en-us/library/hh194845.aspx或者使用Thread.Sleep並添加一個引用來使用System.Threading; – Max 2013-03-11 15:08:22
可能的重複:http://stackoverflow.com/q/4990602/ – Default 2013-03-11 16:57:53