如果超出延迟时间,则延迟任务并返回空值

时间:2016-06-09 11:04:22

标签: c# .net delay

如何在返回变量值之前延迟任务,如果超出延迟时间,则变量的值返回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

2 个答案:

答案 0 :(得分:2)

诀窍是启动“延迟”任务,并与“真实”任务同时运行,看看哪一个完成:

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;
}

答案 1 :(得分:0)

有一种更简洁的方法来实现Clay的方法。

public Task<int?> ValueOrNull( )
{
    return Task.WhenAny(
        SomeAsyncMethod(),
        DelayResult(default(int?), TimeSpan.FromSeconds(5))
    );
}

public async Task<T> DelayResult<T>(T result, TimeSpan delay)
{
    await Task.Delay(delay);
    return result;
}