提问者:小点点

C#-在引发异常之前等待并检查三次


下面是现有的代码。我正在尝试重构这段代码。

用C#实现这一点的最佳方法是什么

第一次,我要等200秒,第二次要等400秒,第三次要等600秒

await Task.Delay(200);
var category = this.categoryRepository.Categories.SingleOrDefault(x => x.CategoryId == categoryId);
if (category == null)
{
    await Task.Delay(400);
    category = this.categoryRepository.Categories.SingleOrDefault(x => x.CategoryId == categoryId);
    if (category == null)
    {
                await Task.Delay(600);
                category = this.categoryRepository.Categories.SingleOrDefault(x => x.CategoryId == categoryId);

      if (category == null)
      {
          throw NullReferenceException;
       }
    }
  }

共1个答案

匿名用户

添加计数器并使用循环:

int numTries = 0;
Category category = null;

do
{
    numTries++;

    await Task.Delay(200 * numTries);
    category = this.categoryRepository.Categories.SingleOrDefault(x => x.CategoryId == categoryId);
} while (category == null && numTries < 3);

if (category == null)
{
    throw NullReferenceException;
}