goo*_*ate 6 c# rest web-services webclient exception
我正在从REST服务中读取并需要为一个使用频繁的服务处理"等待并重试",这会给我一个错误:
每秒查询次数过多
要么
服务器繁忙
一般来说,由于我有许多REST服务要调用,我怎么能一般地处理发生异常时会发生的退避逻辑呢?
有没有内置的框架?我只是想编写干净的代码,不要太担心管道和基础设施.
您可以在一个处理重试逻辑的方法中将尝试包装起来.例如,如果您使用WebClient的是异步方法:
public async Task<T> RetryQuery<T>(Func<Task<T>> operation, int numberOfAttempts, int msecsBetweenRetries = 500)
{
while (numberOfAttempts > 0)
{
try
{
T value = await operation();
return value;
}
catch
{
// Failed case - retry
--numberOfAttempts;
}
await Task.Delay(msecsBetweenRetries);
}
throw new ApplicationException("Operation failed repeatedly");
}
Run Code Online (Sandbox Code Playgroud)
然后你可以通过以下方式使用:
// Try 3 times with 500 ms wait times in between
string result = await RetryQuery(async () => webClient.DownloadStringTaskAsync(url), 3);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
897 次 |
| 最近记录: |