c# - 延迟任务,超过延迟时间则返回空值

标签 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

最佳答案

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

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/

相关文章:

c# - 防止数据绑定(bind) DataGridView 在编辑时进行排序

c# - 在不同的命名空间中实现多个属性

c# - ASP.NET Core 如何执行 Linux shell 命令?

c# - 如何验证 RadioButtonList 是否在 C# 中检查/选择它?

jquery - 如何延迟jquery动画?

jQuery延迟启动函数

c# - 连接未关闭。连接的当前状态是打开的。 C#错误

C# Regex.Replace - 也在替换字符串中搜索匹配项

.net - 一场比赛后进行多场比赛

flutter - 如何检测用户已停止在 TextField 中输入?