简体   繁体   English

使用实体框架C#限制与数据库的连接

[英]Limit Connections to Database with Entity Framework C#

I have an Azure database that is limited to 60 concurrent connections. 我有一个Azure数据库,限制为60个并发连接。 My issue is that I have several crawlers that populate this database to be consumed by our website using Entity Framework. 我的问题是我有几个爬虫填充这个数据库,供我们的网站使用Entity Framework使用。

It does not take long for multiple crawlers to exhaust all of the connections and error out. 多个爬虫不需要很长时间就可以耗尽所有连接并排除错误。 I have tried setting the max pool size value in the connection string, but this does not seem to enforce any restrictions on the actual database connections. 我已尝试在连接字符串中设置max pool size值,但这似乎并未对实际数据库连接强制实施任何限制。

I could wrap the DbContext in a singleton, but then I would be limiting the entire crawler to a single connection. 我可以将DbContext包装成单例,但是我会将整个爬虫限制为单个连接。

Are there any other ways to achieve this? 有没有其他方法可以实现这一目标?

You are trying to limit concurrent access to a shared resource. 您正在尝试限制对共享资源的并发访问。 Usually a Semaphore is used for this. 通常使用信号量来实现此目的。

To do this across a single box or a single app you could use Semaphore or SemaphoreSlim 要在单个框或单个应用程序中执行此操作,您可以使用Semaphore或SemaphoreSlim

However if the clients are running on different boxes the natural place to place the semaphore would be the SQL Server itself. 但是,如果客户端在不同的盒子上运行,则放置信号量的自然位置将是SQL Server本身。 See this article for one way of implementing it. 有关实现它的一种方法,请参阅此文章 The app would need to call the proc to acquire the lock before accessing the database using the DbContext . 在使用DbContext访问数据库之前,应用程序需要调用proc来获取锁。 The semaphore limit would need to be 59 to keep one connection for reading the semaphore. 信号量限制需要为59才能保持一个连接以读取信号量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM