开发者

Passing a method call and its parameter to a different method

I am using an external automation library with bunch of APIs with either 1 or 2 parameters which randomly throws TargetInvocationException. Calling these APIs second or third time usually works. I therefore created two helper methods to encapsulate the multiple retry logic

//Original API calls
bool result1 = Foo1(true);
int result2 = Foo2(4, "abc");

//New API calls
bool result1 = SafeMethodCall(Foo1, true);
int result2 = SafeMethodCall(Foo2, 4, "abc");


//Helper Methods
public static TResult SafeMethodCall<T, TResult>(
    Func<T, TResult> unSafeMethod,
    T parameter)
{
    int numberOfMethodInvocationAttempts = 3;
    int sleepIntervalBetweenMethodInvocations = 10000;

    for (int i = 0; i < numberOfMethodInvocationAttempts; i++)
    {
        try
        {
            return unSafeMethod(parameter);
        }
        catch (System.Reflection.TargetInvocationException ex)
        {
            System.Threading.Thread.Sleep(sleepIntervalBetweenMethodInvocations);
        }
    }
}

public static TResult SafeTargetInvocationMethodCall<T1, T2, TResult>(
    Func<T1, T2, TResult> unSafeMethod,
    T1 parameter1,
    T2 parameter2)
{
    int numberOfMethodInvocationAttempts = 3;
    int sleepIntervalBetweenMethodInvocations = 10000;

    for (int i = 0; i < numberOfMethodInvocationAttempts; i++)
    {
        try
        {
            return unSafeMethod(parameter1开发者_StackOverflow中文版, parameter2);
        }
        catch (System.Reflection.TargetInvocationException ex)
        {
            System.Threading.Thread.Sleep(sleepIntervalBetweenMethodInvocations);
        }
    }
}

Problem: If you see the two helper methods above have the same body and the only difference is unsafeMethod call inside the try block. How can I avoid code duplication here as I might have to add a overloaded method that accepts

Func<TResult>

as another parameter type.


Just pass in Func<TResult> and call it like this:

bool result1 = SafeMethodCall(() => Foo1(true));
int result2 = SafeMethodCall(() => Foo2(4, "abc"));

In other words, encapsulate the arguments in the delegate itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜