Question

Je joue avec le code de démonstration de cet article msdn par Jeffrey Richter .

J'ai ajouté une nouvelle fonction à ses ApmToCcrAdapters pour gérer la SqlCommand.BeginExecuteReader. Seulement, il ferme le lecteur avant que je puisse le lire.

Le code suivant est utilisé pour fournir un 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"]);
       }
   }

Ce qui appelle à son tour le code suivant:

   /// <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);
   }
Était-ce utile?

La solution

La connexion doit rester ouverte pour que le lecteur fonctionne. Je crois que la fermeture de la connexion est votre problème. Laissez la connexion ouverte et appelez disposer sur le lecteur lorsque vous avez terminé et je pense que cela devrait nettoyer la connexion.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top