<p>I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process.</p>

<p>Anyway, here's the problem:</p>

<p>Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc.</p>

<p>The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic.</p>

<p>Here's an example code snippet:</p>

<pre><code>RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10));
bool success = false;
while (!success)
{
    try
    {
        // do some file IO which may succeed or fail
        success = true;
    }
    catch (IOException e)
    {
        if (fileIORetryTimer.HasExceededRetryTimeout)
        {
            throw e;
        }
        fileIORetryTimer.SleepUntilNextRetry();
    }
}
</code></pre>

<p>So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods:</p>

<pre><code>this.RetryFileIO( delegate()
    {
        // some code block
    } );
</code></pre>

<p>I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem.</p>

[{'answer_id': 1554, 'author': 'Chris Marasti-Georg', 'author_id': 96, 'author_profile': 'https://Stackoverflow.com/users/96', 'pm_score': 2, 'selected': False, 'text': '<p>Just wondering, what do you feel your method leaves to be desired?  You could replace the anonymous delegate with a.. named? delegate, something like</p>\n\n<pre><code>    public delegate void IoOperation(params string[] parameters);\n\n    public void FileDeleteOperation(params string[] fileName)\n    {\n        File.Delete(fileName[0]);\n    }\n\n    public void FileCopyOperation(params string[] fileNames)\n    {\n        File.Copy(fileNames[0], fileNames[1]);\n    }\n\n    public void RetryFileIO(IoOperation operation, params string[] parameters)\n    {\n        RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10));\n        bool success = false;\n        while (!success)\n        {\n            try\n            {\n                operation(parameters);\n                success = true;\n            }\n            catch (IOException e)\n            {\n                if (fileIORetryTimer.HasExceededRetryTimeout)\n                {\n                    throw;\n                }\n                fileIORetryTimer.SleepUntilNextRetry();\n            }\n        }\n    }\n\n    public void Foo()\n    {\n        this.RetryFileIO(FileDeleteOperation, "L:\\file.to.delete" );\n        this.RetryFileIO(FileCopyOperation, "L:\\file.to.copy.source", "L:\\file.to.copy.destination" );\n    }\n</code></pre>\n'}, {'answer_id': 2047, 'author': 'Mike Minutillo', 'author_id': 358, 'author_profile': 'https://Stackoverflow.com/users/358', 'pm_score': 5, 'selected': True, 'text': '<p>This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on <a href="https://learn.microsoft.com/en-us/archive/blogs/simonince/aspect-oriented-interception" rel="nofollow noreferrer">AOP in .NET</a>. The general idea is that you\'d extract the cross-functional concern (i.e. Retry for x hours) into a separate class and then you\'d annotate any methods that need to modify their behaviour in that way. Here\'s how it might look (with a nice extension method on Int32)</p>\n<pre><code>[RetryFor( 10.Hours() )]\npublic void DeleteArchive()\n{\n  //.. code to just delete the archive\n}\n</code></pre>\n'}, {'answer_id': 4601, 'author': 'Andrew Peters', 'author_id': 608, 'author_profile': 'https://Stackoverflow.com/users/608', 'pm_score': 2, 'selected': False, 'text': '<p>You could also use a more OO approach:</p>\n\n<ul>\n<li>Create a base class that does the error handling and calls an abstract method to perform the concrete work. (Template Method pattern)</li>\n<li>Create concrete classes for each operation.</li>\n</ul>\n\n<p>This has the advantage of naming each type of operation you perform and gives you a Command pattern - operations have been represented as objects.</p>\n'}, {'answer_id': 3697548, 'author': 'Andrej Kyselica', 'author_id': 435024, 'author_profile': 'https://Stackoverflow.com/users/435024', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s what I did recently. It has probably been done elsewhere better, but it seems pretty clean and reusable.</p>\n\n<p>I have a utility method that looks like this:</p>\n\n<pre><code>    public delegate void WorkMethod();\n\n    static public void DoAndRetry(WorkMethod wm, int maxRetries)\n    {\n        int curRetries = 0;\n        do\n        {\n            try\n            {\n                wm.Invoke();\n                return;\n            }\n            catch (Exception e)\n            {\n                curRetries++;\n                if (curRetries &gt; maxRetries)\n                {\n                    throw new Exception("Maximum retries reached", e);\n                }\n            }\n        } while (true);\n    }\n</code></pre>\n\n<p>Then in my application, I use c#\'s Lamda expression syntax to keep things tidy:</p>\n\n<pre><code>Utility.DoAndRetry( () =&gt; ie.GoTo(url), 5);\n</code></pre>\n\n<p>This calls my method and retries up to 5 times. At the fifth attempt, the original exception is rethrown inside of a retry exception.</p>\n'}]
['https://Stackoverflow.com/questions/1535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/332/']