只要你的方法簽名返回一個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