locked
Retry iteration on exception RRS feed

  • Question

  • I am running a loop to iterate an object list and its property values.

    When I try to access the ojects values I get an exception error because it is not ready (I think).

    i.e.

    foreach (oject obj in ObjectList)

    {

         //Using object property here that MAY raise exception if used too soon

         obj.MyProperty;

    }

    I am having trouble finding a way to determine if the object is ready, but if I can simply retry it after a second or 2 it will work.

    My question is, if an exception is raised when I access obj.MyProperty, how can I get the loop to re-try the same iteration?

    Monday, March 5, 2012 6:04 AM

Answers


  • check this link ....
    http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-logic


    Peter Koueik


    • Edited by Peter Koueik Monday, March 5, 2012 6:24 AM
    • Marked as answer by Mr Cheese Monday, March 5, 2012 6:25 AM
    Monday, March 5, 2012 6:20 AM

All replies


  • check this link ....
    http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-logic


    Peter Koueik


    • Edited by Peter Koueik Monday, March 5, 2012 6:24 AM
    • Marked as answer by Mr Cheese Monday, March 5, 2012 6:25 AM
    Monday, March 5, 2012 6:20 AM
  • You can create while loop inside the for each to re-try operation specified times. Create try-catch block inside it, then read MyProperty insite the try block. In catch block you need to check and set the counter and if re-try limit is reached then throw exception. But before doing this kind of an solution, I would inspect that I really know why the exception is occurs, expecially when using getter of the property that usually do not throw exceptions.

    foreach (Object item in list)
    {
         int retryCounter = 0;
    
         while (true)
         {
            try
            {
                 // do operation that might throw exception
                 // but can be tried again
    
                 break;
            }
            catch (Exception e)
            {
               if (retryCounter < 5)
               {
                  retryCounter++;
                  Thread.Sleep(200);
               }
               else
               {
                  throw;
               }
            }
         }
    }

    Monday, March 5, 2012 6:28 AM