30

I've been having this SemaphoreFullException for quiet some time.

To summarize.. I have hosted an application on IIS 7.5 with ASP.NET v4.0 framework Application Pool (integrated). I am using windows authentication to authenticate my users through domain (isinrole).

I've seen all other threads on this topic, where it is suggested to set Pooling = False. I do not want to do that and I would like to keep on using pooling because of the performance benefits.

I am using Entity Framework 6 to query the database and I am not "disposing" the dbcontext anywhere in user code. It looks like the issue is in the DbConnectionPool code.

The error occurs randomly at any given moment of time. It doesn't matter if the application is being used or not. Sometimes, due to this issue - I have to restart IIS because new users stop getting authenticated.

What I've tried so far:

  • Check whether a DB transaction object is being disposed.
  • Check whether a DBContext (ctx) is being disposed prematurely.
  • Check application build (32/62 bit). In this case - I build the application in ANY CPU mode and my server is 64 bit.

Note: In my application, I've mostly used linq-to-EF objects to query the DB.

Exception: System.Threading.SemaphoreFullException

Message: Adding the specified count to the semaphore would cause it to exceed its maximum count.

StackTrace:    at System.Threading.Semaphore.Release(Int32 releaseCount)
   at System.Data.ProviderBase.DbConnectionPool.CleanupCallback(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.TimerQueueTimer.CallCallback()
   at System.Threading.TimerQueueTimer.Fire()
   at System.Threading.TimerQueue.FireNextTimers()

Any help in this regard will be greatly appreciated.

Ali Haider
  • 467
  • 1
  • 6
  • 15
  • We're seeing this too - did you ever find a solution? Google searching led nowhere fast, other than a vague (and not 100% effective) recommendation to turn off connection pooling, which won't scale for us. – Paul Karlin Jul 01 '15 at 17:35
  • 1
    I dont have a solution, just a few observations. The DBContext was not intended to be used like. DBContext is NOT thread safe. How do manage the thread aspect of your DBContent ? Note IIS calls can involve different threads. I can not emphasise enough consider moving to short lived contexts. at a minumum 1 per thread. – phil soady Sep 12 '15 at 13:37
  • Apologies for the late reply. We had to shift to ADO/Bulk insert/update options to speed up the querying and negate this error. – Ali Haider Oct 01 '15 at 15:12

4 Answers4

18

In my case, the problem was that I stopped the application while debugging. The application was making a lot of async callings.

So I reset my IIS server: iisreset via Command Prompt or PowerShell, and it worked.

EDIT: Look at the @aaroncatlin comment for IIS Express

Luis Teijon
  • 4,769
  • 7
  • 36
  • 57
  • 2
    I had the same cause, but `iisreset` did not solve it for me. Instead I had to find IIS Express in the System Tray, Right-Click and Exit. When I started another debug session after that the problem went away. – aaroncatlin Feb 05 '19 at 12:31
  • I got this problem after stopping the application while debugging. There was only one synchronous DB query happening at the time. – Andrew Morton Jul 09 '20 at 13:17
9

I think that this may be a solution to the problem: http://www.davepaquette.com/archive/2013/03/27/managing-entity-framework-dbcontext-lifetime-in-asp-net-mvc.aspx - as you can see there, it is essential to take care for disposal of the DbContext when it´s lifetime is over.

Remember, Db connections end up in unmanaged db handling code, so the problem is unless garbage collection disposes the context it stays sleeping in the main memory, thereby also blocking a connection from the connection pool. So sooner or later, under the right conditions, you empty the connection pool and get your exception.

flohack
  • 457
  • 1
  • 4
  • 18
  • Maybe that's the reason for the issue. Nevertheless, I had to shift from EF6 DBContext to ADO and was able to resolve the errors. Marking the link for future references. Thanks! – Ali Haider Oct 01 '15 at 15:10
  • 2
    I am currently searching for a solution to this issue. [Here's what Diego Vega, Senior Lead on EF dev team, has to say about it being harmless not to dispose of the context.](http://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext.html) – busitech Jun 08 '16 at 01:30
6

I recently hit a similar issue of SemaphoreSlim. The problematic code is below and the same exception is raised in semaphoreSlime.Release(). The cause here is that WaitAsync failed due to token cancellation, hence Release() will cause allowed max count exceeded. So, a solution could be adding some defense code before calling Release() , e.g., check whether exception happened during WaitAsync, check allowed account whether exceeding allowed count.

try
{
   await semaphoreSlim.WaitAsync(cancellationToken);
   // do some work
}
catch (OperationCanceledException)
{
   // exception handling
}
finally
{
   semaphoreSlim.Release();
}
zjg.robin
  • 95
  • 1
  • 5
  • 1
    Another solution would be to move the `await semaphoreSlim.WaitAsync(cancellationToken);` line **above** the try-block. In that case a canceled token will not trigger the finally-block. – Baccata Jun 05 '23 at 08:20
1

I had the same problem and was because I was doing .Dispose(); before closing the connection this is how I solved it:

I had two instances of .Dispose(); - one in a SqlDataAdapter, the other in one SqlCommand and after that was closing the connection and getting the error. Just removed the .Dispose(); from my SqlCommand and my SqlDataAdapter, and no more error! I hope this helps somehow.

Chait
  • 1,052
  • 2
  • 18
  • 30
JCO9
  • 960
  • 1
  • 15
  • 24
  • Glad that you were able to resolve it. Thanks for the feedback. Will give it a try the next time I have this issue. – Ali Haider Jun 23 '16 at 14:53