连接未关闭错误

时间:2014-10-31 10:29:38

标签: c# database-connection

运行以下代码时,为什么会出现此错误?这经常发生。我检查了开放的连接......

System.InvalidOperationException: The connection was not closed.
   at System.Data.EntityClient.EntityConnection.Open()
   at Publish(Int32 reportID)

CODE:

while (!completed && 5 >= retryCount)
{
   retryCount++;
   try
   {
       internalReportsEntities.CommandTimeout = (5 * 60);
       internalReportsEntities.Publish(internalSet.ID); // publish method called
       completed = true;
   }
   catch (EntityCommandExecutionException entityCommandExecutionException)
   {
        if (5 < retryCount) throw;
        Utilities.ThreadUtilities.Sleep(retryCount);
   }
}

public void Publish(int reportID)
{
if (this.Connection.State != System.Data.ConnectionState.Open) this.Connection.Open();
EntityCommand publishEntityCommand = new EntityCommand
    {
            CommandType = CommandType.StoredProcedure,
            CommandText = @"ReportsEntities.Publish",
            Connection = (EntityConnection)this.Connection
    };
}

1 个答案:

答案 0 :(得分:1)

您需要在try / catch / finally块中包装Publish方法中的代码,并在完成连接后处理该连接。这里解释了一个很好的例子:http://msdn.microsoft.com/en-gb/library/vstudio/bb738461(v=vs.100).aspx