0

I am trying to find a solution that allows me to write one method in my forms project that can variably call multiple different methods from my class library project.

The reason for this being that I want to implement retry logic around these methods and prevent myself from repeating it for each different variety of method. The only consistent thing about the class library methods are that they all return Task<bool> so its easy to await on and perform logic with.

So far I have the following:

public async Task Runner(string methodName, params object[] parameters)
        {
            ThreadTimer.Start();
            var tries = 0;
            var ok = false;
            while (tries <= 180)
            {
                try
                {
                    var parameterTypes = (from p in parameters select p.GetType()).ToArray();
                    var mi = typeof(string).GetMethod(methodName, parameterTypes); //Currently returns null
                    var result = (Task<bool>)mi.Invoke(null, parameters);
                    ok = await result;
                    if (ok) break;
                }
                catch (Exception ex)
                {
                    if (ex.InnerException == null)
                    {
                        ExceptionLabel2.Text = ex.Message;
                    }
                    else
                    {
                        ExceptionLabel1.Text = ex.Message;
                        ExceptionLabel2.Text = ex.InnerException.Message;
                    }
                }
                finally
                {
                    tries++;
                }
            }

            if (ok)
            {
                ThreadTimer.Dispose();
            }
            else
            {
                CShellControls.ExitWindowsEx(0, 0); //Logoff
            }
        }

The idea behind this is to declare a method name in a string and pass an array of parameters with it. I then used .GetMethod() to try and fetch the desired method info but unfortunately this returns null.

I have tried a few different methods but I'm open to suggestions and critique. As far as optimizing code goes I haven't really thought much into it, I just want to try and get this working first before approaching a more efficient method.

Thank you in advance!

3
  • 2
    Have you considered using Polly?
    – mjwills
    Mar 2, 2019 at 11:44
  • @mjwills I haven't actually, I'll look into this now thank you Mar 2, 2019 at 11:45
  • 1
    @mjwills I've done a rewrite and Polly has saved the day. Thanks! Mar 4, 2019 at 10:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.