Database connection pooling with multi-threaded service

前端 未结 3 386
甜味超标
甜味超标 2021-01-12 01:23

I have a .NET 4 C# service that is using the TPL libraries for threading. We recently switched it to also use connection pooling, since one connection was becoming a bottle

3条回答
  •  旧巷少年郎
    2021-01-12 01:51

    Another approach is to use a semaphore around the code that retrieves connections from the pool (and, hopefully, returns them). A sempahore is like a lock statement, except that it allows a configurable number of requestors at a time, not just one.

    Something like this should do:

    //Assuming mySemaphore is a semaphore instance, e.g. 
    // public static Semaphore mySemaphore = new Semaphore(100,100);
    try {
      mySemaphore.WaitOne(); // This will block until a slot is available.
      DosomeDatabaseLogic();
    } finally {
      mySemaphore.Release();
    }
    

提交回复
热议问题