延迟任务

时间:2018-05-10 20:39:01

标签: c# .net async-await delay

无法在任务中获得延迟 同步不会延迟。
异步停在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($"");

1 个答案:

答案 0 :(得分:2)

您可以简单地将其作为

Task.Delay(delay).Wait()