[英]Adjusting the Invoke call to cater for methods that return void and non-void types
我將如何調整以下Invoke
調用,使其適合返回void和non-void類型的方法?
目前, ErrorHandlingComponent.Invoke
希望將Func<T>
作為其第一個參數。 我發現,當我嘗試將其傳遞給void方法時,編譯器會抱怨。
public static T Invoke<T>(Func<T> func, int tryCount, TimeSpan tryInterval)
{
if (tryCount < 1)
{
throw new ArgumentOutOfRangeException("tryCount");
}
while (true)
{
try
{
return func();
}
catch (Exception ex)
{
if (--tryCount > 0)
{
Thread.Sleep(tryInterval);
continue;
}
LogError(ex.ToString());
throw;
}
}
}
你不能 Func
委托的設計使其始終返回某些內容。
最簡單的方法是創建Invoke
方法的重載,該方法采用Action
委托而不是Func
:
public static void Invoke(Action action, int tryCount, TimeSpan tryInterval)
{
if (tryCount < 1)
{
throw new ArgumentOutOfRangeException("tryCount");
}
while (true)
{
try
{
action();
return;
}
catch (Exception ex)
{
if (--tryCount > 0)
{
Thread.Sleep(tryInterval);
continue;
}
LogError(ex.ToString());
throw;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.