簡體   English   中英

調整Invoke調用以適應返回void和non-void類型的方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM