如何延迟任务直到返回变量的值,如果超过延迟时间,则变量的值返回 null。例如:
TaskA.Delay(5000);
if variable not equal to empty string
continue with Task A
else
if delay time not exceeded yet
continue running the current task
else
set variable's value to empty string
最佳答案
诀窍是启动一个“延迟”任务,并与“实际”任务同时运行它,看看哪个任务先完成:
public async Task<int?> ValueOrNull( )
{
var task = SomeAsyncMethod() //--> the work to wait on
var timeout = Task.Delay( new TimeSpan( 0,0,5 ) );
var first = await Task.WhenAny( task, timeout );
if ( first == timeout ) return null;
await first; //--> It's already done, but let it throw any exception here
return;
}
您可以通过将任务和超时传递到以下位置来概括这一点:
public async Task<T> ValueOrNull( Task<T> task, TimeSpan patience )
{
var timeout = Task.Delay( patience );
var first = await Task.WhenAny( task, timeout );
if ( first == timeout ) return default( T );
await first; //--> It's already done, but let it throw any exception here
return;
}
关于c# - 延迟任务,超过延迟时间则返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37724175/