我一直在玩的演示代码从这个MSDN文章由杰弗里里希特

我添加了一个新功能,他ApmToCcrAdapters处理SqlCommand.BeginExecuteReader。只有它被关闭之前读者我可以读取它。

下面的代码用于提供一个FromIteratorHandler:

    private static IEnumerator<ITask> AsyncReaderDemoHandler()
    {
       SqlDataReader reader = null;
       SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=BizData;Integrated Security=True;Async=True;");
       string query = "SELECT * FROM Account;";
       SqlCommand command = new SqlCommand(query,connection);

       connection.Open();
       yield return Arbiter.Choice(ApmToCcrAdapters.GetReader(command),
          delegate(SqlDataReader r) { Msg("Got SQL data"); reader = r; },
          delegate(Exception e) { Msg("Failed to get SQL data"); });

       connection.Close();

       if (reader == null) yield break;

       //This is where the code fails: Reader is Closed!
       while (reader.Read())
       {
           Console.WriteLine(reader["Account"]);
       }
   }

,后者又调用以下代码:

   /// <summary>
   /// Gets the Reader, requires connection to be managed
   /// </summary>
   public static PortSet<SqlDataReader, Exception> GetReader(SqlCommand sqlCommand)
   {
       Port<SqlDataReader> portResponse = null;
       Port<Exception> portException = null;
       GetReaderResponse(sqlCommand, ref portResponse, ref portException);
       return new PortSet<SqlDataReader, Exception>(portResponse, portException);
   }

   // Wrapper for SqlCommand's GetResponse
   public static void GetReaderResponse(SqlCommand sqlCom,
      ref Port<SqlDataReader> portResponse, ref Port<Exception> portException)
   {
       EnsurePortsExist(ref portResponse, ref portException);
       sqlCom.BeginExecuteReader(ApmResultToCcrResultFactory.Create(
          portResponse, portException,
          delegate(IAsyncResult ar) { return sqlCom.EndExecuteReader(ar); }), null);
   }
有帮助吗?

解决方案

在连接必须保持开放为读者工作。我相信,关闭连接是你的问题。离开连接打开并调用Dispose读者做,我认为应该清理连接时。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top