只要你的方法签名返回一个T,主线程将不得不阻塞,直到所有重试完成。但是,您可以通过让线程睡眠,而不是做一个手动重置事件减少CPU:
Thread.Sleep(retryInterval);
如果你愿意改变你的API,你可以把它,这样你就不会阻塞主线程。例如,你可以使用异步方法:
public async Task<T> RepeatAsync<T, TException>(Func<T> work, TimeSpan retryInterval, int maxExecutionCount = 3) where TException : Exception
{
for (var i = 0; i < maxExecutionCount; ++i)
{
try { return work(); }
catch (TException ex)
{
// allow the program to continue in this case
}
// this will use a system timer under the hood, so no thread is consumed while
// waiting
await Task.Delay(retryInterval);
}
}
这能够同步消耗:
RepeatAsync<T, TException>(work, retryInterval).Result;
但是,您也可以启动任务,然后等待它以后:
var task = RepeatAsync<T, TException>(work, retryInterval);
// do other work here
// later, if you need the result, just do
var result = task.Result;
// or, if the current method is async:
var result = await task;
// alternatively, you could just schedule some code to run asynchronously
// when the task finishes:
task.ContinueWith(t => {
if (t.IsFaulted) { /* log t.Exception */ }
else { /* success case */ }
});
可能重复[如何等待一段时间或函数调用,无论采取最长的系统时间更改,即使?](http://stackoverflow.com/questions/5107522/how-to-等待一段时间或函数调用 - 取最长 - 甚至) – CodeCaster