简体   繁体   中英

How can I use this method to reuse my try/catch?

I found this method (function?) from another SO question and I'm unsure how I'm to use it. I'd like to use it to catch connectivity issues to my DB (over a wireless network) and retry or throw other exceptions. My application only has a couple of database accessing functions so I was about to just copy and paste everything but I don't want to have to update every function 10 times if I need to change something.

Method I want to use:

        private void Retry<T>(Action<T> retryAction) where T : DataContext, new()
    {
        var retryCount = 0;
        using (var ctx = new T())
        {
            for (; ; )
            {
                try
                {
                    retryAction(ctx);
                    break;
                }
                catch (SqlException ex)
                {
                    if (!Enum.IsDefined(typeof(RetryableSqlErrors), ex.Number))
                        throw;

                    retryCount++;
                    if (retryCount > MAX_RETRY) throw;

                    Thread.Sleep(ex.Number == (int)RetryableSqlErrors.Timeout ?
                                                            longWait : shortWait);
                }
            }
        }
    }

Example of functions I want to pass to it:

public async Task<List<EmployeeDisplay>> GetInspectorsAsync()
    {
        using (M1Context m1 = new M1Context())
        {

            var q = (from a in m1.Employees
                     where (a.lmeTerminationDate == null)
                     && (a.lmeInspectorEmployee == -1)
                     orderby a.lmeEmployeeName
                     select new EmployeeDisplay
                     {
                         EmployeeID = a.lmeEmployeeID,
                         EmployeeName = a.lmeEmployeeName.ToUpper().Trim()
                     });

            return await q.ToListAsync();
        }

    }


       public async Task<List<Reason>> GetScrapReasonsAsync()
    {
        using (M1Context m1 = new M1Context())
        {

            Debug.WriteLine("getting scrap reasons");
            var q = (from a in m1.Reasons
                     where a.xarReasonType.Trim().Equals("S")
                     select a);

            return await q.ToListAsync();

        }
    }

To to use the method you need to do the following

  1. Your Context

在此处输入图片说明

  1. Your Retry Method

在此处输入图片说明

  1. Your Do Stuff method

在此处输入图片说明

  1. Enum

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM