【问题标题】:Returning XMLReader返回 XMLReader
【发布时间】:2010-01-11 17:18:12
【问题描述】:

我正在尝试从调用存储过程以运行 FOR XML 查询的数据访问类返回 XMLReader。问题是,当我返回 xmlreader 时,我无法在 sql 连接上调用 close(),否则读取将终止。调用 xmlreader 的类对 sql 连接一无所知,因此它不能负责关闭连接。我该如何处理?

【问题讨论】:

    标签: .net xml xmlreader


    【解决方案1】:

    您可以构建一个XmlDocument 并将其返回,这样您就可以关闭该数据库连接。

    【讨论】:

    • 问题是,这个 xml 可能高达 200mb,这就是我尝试阅读器方法的原因。我真的想在内存中保存一个 200mb 的 xmldocument 吗?
    • 在这种情况下,您需要保持该连接打开,或者使您的数据访问层一次性使用,因此您可以使用using调用它
    【解决方案2】:

    使用匿名方法包装调用。

    例如,假设你有一个数据层类,给数据层添加一个类似的方法:

    public delegate void DoSomethingInvoker();
    class DataLayer
    {
       //myReader needs to be declared externally in other to access it from the doSomething delegate
       public void MethodThatGetsAsXmlReader(XmlReader myReader, DoSomethingInvoker doSomething)
       {
          myReader = GetXmlReaderFromDB();
          doSomething();
          CloseDbConnection();      //close connections, do cleanup, and any other book keeping can be done after the doSomething() call
       }
    }
    

    要调用/使用它,您只需在高级课程中执行此操作

    DataLayer dl = new DataLayer();
    XmlReader myReader = null;  //variables declared outside the scope of the anonymous method are still accessible inside it through the magic of closures
    dl.MethodThatGetsAsXmlReader(myReader, delegate()
       {
          //do all work that involves myReader here
          myReader.read();   
          Console.out.println(myReader.value);
       });
    //at this point myReader is closed and cannot be used
    

    基本上,您将要执行的代码传递给数据层,数据层获取 xmlreader,针对它调用您的代码,然后进行清理。

    我使用类似的技术在我的代码中包装事务逻辑

    DataLayer dl = new DataLayer();
    dl.Transaction(delegate()
       {
            dl.DbCall1();
            dl.DbCall2();
            dl.DbCall3();
        });
    

    它使代码美观且可读,同时仍保持其组织性和分层性;

    【讨论】:

      猜你喜欢
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多