减少C#中的重复错误处理代码? [英] Reducing duplicate error handling code in C#?

查看:107
本文介绍了减少C#中的重复错误处理代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从未对异常处理工作的方式感到非常满意,有很多异常和try / catch带给表(堆栈展开等),但它似乎打破了很多OO模型在



无论如何,这里是问题:



假设你有一些类包装或包含网络文件IO操作(例如在某处特定UNC路径读取和写入某些文件)。由于各种原因,您不希望这些IO操作失败,因此,如果您检测到它们失败,则重试它们,并且继续重试,直到成功或达到超时。我已经有一个方便的RetryTimer类,我可以实例化并使用它来重试之间的当前线程,并确定何时超时时间等等。



问题是你在这个类的几个方法中有一堆IO操作,你需要将它们中的每一个都包含在try-catch / retry逻辑中。



这是一个示例代码段:

  RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10)); 
bool success = false;
while(!success)
{
try
{
//做一些可能成功或失败的文件IO
success = true;
}
catch(IOException e)
{
if(fileIORetryTimer.HasExceededRetryTimeout)
{
throw e;
}
fileIORetryTimer.SleepUntilNextRetry();
}
}

那么,你如何避免重复这个代码的大部分为每个文件IO操作整个班?我的解决方案是在类中使用匿名委托块和单个方法,该方法执行传递给它的代理块。这样我可以用其他方法来做这样的事情:

  this.RetryFileIO(delegate()
{
//一些代码块
});

我喜欢这个,但它留下了很多希望。我想听听其他人如何解决这种问题。

解决方案

这看起来像是一个很好的机会看看面向方面的编程。以下是 AOP in .NET 。一般的想法是,您可以将跨功能关注(即重试x小时)解压缩到一个单独的类中,然后您将注释需要以这种方式修改其行为的任何方法。这是它的外观(在Int32上有一个很好的扩展方法)

  [RetryFor(10.Hours())] 
public void DeleteArchive()
{
// ..只删除存档的代码
}


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.

Anyway, here's the problem:

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.

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.

Here's an example code snippet:

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();
    }
}

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:

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

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.

解决方案

This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on AOP in .NET. 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)

[RetryFor( 10.Hours() )]
public void DeleteArchive()
{
  //.. code to just delete the archive
}

这篇关于减少C#中的重复错误处理代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆