本文介绍了延迟任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无法获得任务延迟.
同步完全不会延迟.
异步停止在await Task.Delay(delay);
.
Cannot get a Delay in a task.
The Sync does not delay at all.
The Async stops at 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()
这篇关于延迟任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!