Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The connection was not closed. The connection's current state is open. #12914

Closed
JeanCollas opened this issue Aug 7, 2018 · 8 comments
Closed

Comments

@JeanCollas
Copy link

I am wondering if it is a normal behavior that this throws an exception:


The connection was not closed. The connection's current state is open.
----------------
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.OpenAsync(CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Query.AsyncQueryMethodProvider.FastQueryAsyncEnumerable`1.FastQueryAsyncEnumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.Aggregate_[TSource,TAccumulate,TResult](IAsyncEnumerable`1 source, TAccumulate seed, Func`3 accumulator, Func`2 resultSelector, CancellationToken cancellationToken)

That is the kind of exception I get recently, following updates to the latest version of .Net Core.
As well as

The connection was not closed. The connection's current state is connecting.
System.Data.SqlClient
@smitpatel
Copy link
Member

This issue is lacking enough information for us to effectively reproduce. Please post a runnable project/solution or complete code listing that demonstrates the behavior you are seeing.

@JeanCollas
Copy link
Author

Unfortunately, like many exceptions I run into when upgrading EF versions, it happens randomly, and I cannot reproduce it every time (but it happens several times).
What I cannot understand is quite simple: why throwing an exception if the connection state is connected (or connecting) in a TryOpenConnection, the stacktrace should speak for itself in that case...

@ajcvickers
Copy link
Member

@JeanCollas To me, this looks like it's probably caused by multiple threads making use of the same connection concurrently, which is not supported.

@kosurucs
Copy link

kosurucs commented Dec 5, 2019

Based on my observation and analysis of this issue in my project. It's issue with Entity Framework.

Here explanation:
Entity Framework is not support for asynchronous programming , It's working based on Pooling system. Means, In Entity Framework has build in Thread Pooling Mechanism. So It's has set of Threads for executing of SQL Statements and once an action completed another then one. Like synchronous process. One after another one.

Issue will happens in those scenarios, If While execution of one of the SQL statement in some case any exception happened in middle of process or timeout, multiple execution of same methods (Get Error information from database or Logging Error details in DB) with single instance of Entity Framework DBContext.

This statement based on my observation :

  1. If while execution of Sql Statement. In meddle some exception is happens, Action is ended with out closing the SQL Connection.
  2. Another action used same thread, Entity Framework try to open new connection but already connection is opened. Here these exception we will get this scenario.

If you want reproduce your local or another environment, It's hard too. I'm working some POC. I will Share your later.

Solution is,

  1. Best one is, Initial project. Better void the Entity Framework ( Different ORMs, Drapper is good)
  2. If you existing users with Entity Framework, Like me. Make sure to handle SQL connection with any extension method.

@roji
Copy link
Member

roji commented Dec 5, 2019

@kosurucs there are some inaccurate or unclear statements in your comment. EF definitely does support asynchronous programming; however, it does not support concurrent usage of the same DbContext or connection (which is very different). This is exactly the same as Dapper and most other ORMs that I'm aware of. It's important to understand what these concepts mean in order to properly use EF and .NET in general.

When an exception happens, depending on the exception type, the physical connection may get closed (e.g. networking issue) or not (e.g. database constraint violation). The pooled DbConnection will be closed in any case (so the physical connection is returned to the pool), which is how things were designed to work.

If you have a specific, concrete case where you believe EF Core is not behaving as it should, please open an issue with a code sample and we can discuss it.

@kosurucs
Copy link

kosurucs commented Dec 9, 2019

@roji , Sorry if my understanding is wrong on this issue or my approaching is wrong on this issue.

Could you please help on this issue, Currently we are using EF (6.0.0.0) in our project ... Our DB hosted in Azure Portal. We are Frequently observing this issue on peak hours of day. Currently entire application is depending on EF to interact with DB.

The connection was not closed. The connection's current state is connecting.AD_STACK_TRACE:System.InvalidOperationException: at
System.Data.ProviderBase.DbConnectionClosedConnecting.Boolean TryOpenConnection(System.Data.Common.DbConnection,
System.Data.ProviderBase.DbConnectionFactory, System.Threading.Tasks.TaskCompletionSource`1[System.Data.ProviderBase.DbConnectionInternal],
System.Data.Common.DbConnectionOptions)() at System.Data.SqlClient.SqlConnection.Boolean
TryOpenInner(System.Threading.Tasks.TaskCompletionSource`1[System.Data.ProviderBase.DbConnectionInternal])() at System.Data.SqlClient.SqlConnection.Boolean
TryOpen(System.Threading.Tasks.TaskCompletionSource`1[System.Data.ProviderBase.DbConnectionInternal])() at System.Data.SqlClient.SqlConnection.Open() at
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch() at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open() at
System.Data.Entity.Infrastructure.DbExecutionStrategy+<>c__DisplayClass1.<Execute>b__0() at System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute() at
System.Data.Entity.Core.EntityClient.EntityConnection.Open() at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection() at
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction() at System.Data.Entity.Core.Objects.ObjectContext+<>c__DisplayClass65`1.
<ExecuteStoreQueryReliably>b__63() at System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute() at
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably() at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery() at
System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() at System.Linq.Enumerable.FirstOrDefault() at Telematics.BusinessServices.ErrorService.GetErrorCode() at
ApiServices.Common.ErrorHandler.ErrorHandlerAttribute.HandleBusinessException() at ApiServices.Common.ErrorHandler.ErrorHandlerAttribute.OnException() at
System.Web.Http.Filters.ExceptionFilterAttribute.OnExceptionAsync() at System.Web.Http.Filters.ExceptionFilterAttribute+<ExecuteExceptionFilterAsyncCore>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start() at System.Web.Http.Filters.ExceptionFilterAttribute.ExecuteExceptionFilterAsyncCore()`

@roji
Copy link
Member

roji commented Dec 9, 2019

@kosurucs from a brief glance it seems like you may be trying to use the same connection (and DbContext) concurrently from two different threads. Database connections simply aren't threadsafe, and therefore can not be used concurrently. However, there isn't enough detail to know for sure.

If you can't find the source of the issue, please open a new issue in a new issue on https://github.com/aspnet/EntityFramework6 or ask a question on stackoverflow. Be sure to include a minimal, runnable code sample that demonstrates the issue.

@AmBplus
Copy link

AmBplus commented Jul 13, 2022

I Use Database.EnsureCreatedAsync() and Such Problem Occurred , Then Remove It ,And Problem Resolved ,
As Other Says , I Think This Is Problem Of Entity FrameWork OR Entity FrameWork Core on Async , I Write This Maybe Somebody Like Me Use this method in entityframework and have such Problem , Hope This Useful For you

@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

6 participants