【问题标题】:C# How do I do a Try Catch Finally without a bool to free up resources?C# 如何在没有 bool 的情况下执行 Try Catch finally 以释放资源?
【发布时间】:2016-07-08 19:49:02
【问题描述】:

我正在尝试做一个 try-catch-finally,以便如果 mainLog 成功创建,但之后抛出异常,它将被正确处理。但是,如果 mainLog 没有成功创建并且存在mainLog.Dipose() 方法调用,则会出现另一个异常。通常,我会做一个 if 语句,但 DocX.Create() 不会返回布尔值,所以我不知道该怎么做。谢谢。

public static string Check_If_Main_Log_Exists_Silent()
    {
        DocX mainLog;
        string fileName = DateTime.Now.ToString("MM-dd-yy") + ".docx";
        string filePath = @"D:\Data\Main_Logs\";
        string totalFilePath = filePath + fileName;

        if (File.Exists(totalFilePath))
        {
            return totalFilePath;
        }
        else if (Directory.Exists(filePath))
        {
            try
            {
                mainLog = DocX.Create(totalFilePath);
                mainLog.Save();
                mainLog.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("The directory exists but the log does not exist and could not be created. " + ex.Message, "Log file error");
                return null;
            }
        }
        else
        {
            try
            {
                mainLog = DocX.Create(totalFilePath);
                mainLog.Save();
                mainLog.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("The directory and log does not exist and could not be created. " + ex.Message, "Log file error");
                return null;
            }
            finally
            {
                if(mainLog)
            }
        }

    }

【问题讨论】:

  • using (var mainLog = DocX.Create(totalFilePath)) { mainLog.Save(); }.
  • 您应该简化以保持您的代码尝试 - 为消息使用临时变量。

标签: c# try-catch try-catch-finally


【解决方案1】:

添加 using statement 将仅在代码块末尾为 null 时调用 dispose。它是一种方便的语法糖。

【讨论】:

    【解决方案2】:

    在一般情况下,您默认将mainLog 设置为null,并且仅当它不为空时才调用该方法。使用 C# 6,您可以使用方便的形式:

    mainLog?.Dispose();
    

    对于旧版本,一个简单的 if:

    if (mainLog != null)
        mainLog.Dispose();
    

    如果对象实现了IDisposable 接口,那么使用using 是Gaspa79 的答案所示的最简单的方法。

    【讨论】:

      猜你喜欢
      • 2011-02-06
      • 1970-01-01
      • 2014-12-09
      • 2011-06-01
      • 2021-11-26
      • 2013-12-16
      • 2016-08-18
      • 2011-08-25
      • 1970-01-01
      相关资源
      最近更新 更多