具有"using"关键字的范围块是否可以对异常做出反应?

Mik*_*ike 3 .net c# using exception

我需要在我的代码中进行一些日志记录.我需要使用公司内部开发的库来记录一些信息.这是它的工作原理.

Recorder recorder = Recorder.StartTiming();
DoSomeWork();
recorder.Stop();  // Writes some diagnostic information.
Run Code Online (Sandbox Code Playgroud)

为了确保始终调用Stop(),我创建了一个包装类,允许使用干净的"使用"块.

using (RecorderWrapper recorderWrapper = new RecorderWrapper)  // Automatically calls Recorder.StartTiming() under the covers
{
   DoSomeWork();
}  // When the recorderWrapper goes out of scope, the 'using' statement calls recorderWrapper.Dispose() automatically - which calls recorder.Stop() under the covers
Run Code Online (Sandbox Code Playgroud)

它到目前为止运作良好.但是,我的公司需要改变,在原始代码上看起来像这样:

Recorder recorder = Recorder.StartTiming();
try
{
   DoSomeWork();
}
catch (Exception ex)
{
   recorder.ReportFailure(ex);  // Write out some exception details associated with this "transaction"
}
recorder.Stop();  // Writes some diagnostic information.
Run Code Online (Sandbox Code Playgroud)

我想在RecorderWrapper的所有"使用"范围块中避免尝试/捕获.有没有办法可以容纳"ReportFailure()"调用并仍然利用"使用"范围块?

具体来说,我希望我的团队中的每个人都"陷入成功之中",即让做正确的事情变得容易.对我来说,这意味着很难忘记调用recorder.Stop()或忘记try/catch.

谢谢!

Lee*_*Lee 7

您可以在录像机上创建一个隐藏此方法的方法:

public void Record(Action act)
{
    try
    {
        this.StartTiming();
        act();
    }
    catch(Exception ex)
    {
        this.ReportFailure(ex);
    }
    finally
    {
        this.Stop();
    }
}
Run Code Online (Sandbox Code Playgroud)

所以你的例子就是:

recorder.Record(DoSomeWork);
Run Code Online (Sandbox Code Playgroud)