How to prevent LocalDB from detaching MDF file after some idle time?

喜你入骨 提交于 2019-12-13 12:40:41

问题


I'm building a .NET 4.5 (winforms) application that uses LocalDB to work with a local MDF file, using this connection string:

Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\DB\DatabaseFile.mdf;Integrated Security=True;MultipleActiveResultSets=True

When I run my application, the first SQL query takes some time to execute - nothing drastic, about 2 or 3 seconds. After that, all next SQL queries are executed instantly. I assume that the extra seconds during the first execution are needed to attach the MDF file to a local SQL Server service. Right?

I noticed, however, that if 10 minutes (or so) pass since an SQL query was last performed, the next SQL query will again take those 2-3 seconds more to execute. I assume that after some idle time, the MDF gets detached, and when the new SQL command is called, it re-attaches it once again.

I'm wondering, is there a way to override this behavior?

I know I could create a Timer, that performs a simple query every few minutes, but is there a better, cleaner solution?


回答1:


I would more suspect that your data / index is no longer in memory.

You could run a very fast query like select 'a' to know if it was the connect time.

As for forcing your table / index to stay in memory.
I would so much advise you to let .NET and SQL do their own memory management.

2-3 seconds is not much.
Look at the query plan - maybe you can make it faster (even not in memory).




回答2:


Unless you keep the connection open, your LocalDB instance will shut down after a few minutes. It is started again when you connect to it again. That would explain 2-3 second delay. You can tune the shutdown timeout, as explained in this question. Opening a connection every couple minutes is another way to keep it running. There should be no need to even run any queries, but you may need to make sure the connection is opened outside of the connection pool (at least in early versions of .NET the connection pool used to return the connection without doing any ping on it).

You can also disable AUTO_CLOSE option for the database and prevent the cache from being unloaded from the memory. See this detailed blog post on memory management in SQL Server Express, the AUTO_CLOSE part is directly applicable to LocalDB.



来源:https://stackoverflow.com/questions/27506649/how-to-prevent-localdb-from-detaching-mdf-file-after-some-idle-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!