发生异常时,如何处理C#应用程序中的退避或“等待和重试”逻辑?

前端之家收集整理的这篇文章主要介绍了发生异常时,如何处理C#应用程序中的退避或“等待和重试”逻辑?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在从REST服务中读取并需要为一个使用频繁的服务处理“等待并重试”,这会给我一个错误

Too many queries per second

要么

Server Busy

一般来说,由于我有许多REST服务要调用,我怎么能一般地处理发生异常时会发生的退避逻辑呢?

有没有内置的框架?我只是想编写干净的代码,不要太担心管道和基础设施.

解决方法

您可以在一个处理重试逻辑的方法中将尝试包装起来.例如,如果您使用的是WebClient的异步方法
  1. public async Task<T> RetryQuery<T>(Func<Task<T>> operation,int numberOfAttempts,int msecsBetweenRetries = 500)
  2. {
  3. while (numberOfAttempts > 0)
  4. {
  5. try
  6. {
  7. T value = await operation();
  8. return value;
  9. }
  10. catch
  11. {
  12. // Failed case - retry
  13. --numberOfAttempts;
  14. }
  15.  
  16. await Task.Delay(msecsBetweenRetries);
  17. }
  18.  
  19. throw new ApplicationException("Operation Failed repeatedly");
  20. }

然后你可以通过以下方式使用:

  1. // Try 3 times with 500 ms wait times in between
  2. string result = await RetryQuery(async () => webClient.DownloadStringTaskAsync(url),3);

猜你在找的C#相关文章