任务延迟

Delay in a task

无法获得任务延迟。
同步完全没有延迟。
异步停止在 await Task.Delay(delay);

我试过:

Task wait4me = Task.Delay(1000);
await wait4me;

它没有用 - 它停在 await wait4me;

Task<int> TaskOfTResult_MethodSync(int delay)
{
    Debug.WriteLine($"TaskOfTResult_MethodSync delay = {delay}  {DateTime.Now}");
    int hours = 10; 
    Task.Delay(delay);
    Debug.WriteLine($"TaskOfTResult_MethodSync after delay  {DateTime.Now}");
    return Task.FromResult(hours);
}
async Task<int> TaskOfTResult_MethodAsync(int delay)
{
    Debug.WriteLine($"TaskOfTResult_MethodAsync  delay = {delay}   {DateTime.Now}");
    await Task.Delay(delay);
    Debug.WriteLine($"After await Task.Delay({delay})  {DateTime.Now}");
    int hours = 11;
    return hours;
}

测试

Task<int> task = TaskOfTResult_MethodSync(1000);
Debug.WriteLine("before task.Wait");
task.Wait();
Debug.WriteLine("after  task.Wait");
int i = task.Result;
Debug.WriteLine($"i = {i}");
Debug.WriteLine($"");


Task<int> taskA = TaskOfTResult_MethodAsync(1000);
Debug.WriteLine("before taskA.Wait");
taskA.Wait();
Debug.WriteLine("after  taskA.Wait");
i = taskA.Result;
Debug.WriteLine($"i = {i}");
Debug.WriteLine($"");

你可以简单地按照

Task.Delay(delay).Wait()