如何有效地测试SQL Server实例是否正在C#中运行

问题描述:

我有一个基于SQL Server(2008 R2)的(C#WinForms)应用程序,该应用程序主要在本地安装SQL Server 2008 R2的本地计算机上运行.我遇到的一个问题是,如果用户没有正在运行的服务器实例并尝试执行某些命令或执行某些操作,则查询将发送到SQL Server,并且需要花费很多时间抛出 SqlException 告诉我请求的实例未启动.

I have an SQL Server (2008 R2) based (C# WinForms) application that predominantly runs on a local machine using a local installation of SQL Server 2008 R2. One problem I have is that if the user does not have a server instance running and tries to execute some commands or perform some operations, the queries are sent off to SQL Server and it takes an age to throw an SqlException telling me the requested instance is not started.

我已阅读以下问题和相关答案,但是这些解决方案远非理想.WMI似乎过于杀伤力,如果可以避免的话,我不想在软件的安装包中包含额外的.dll.

I have read the following question and associated answers, but these solutions are far from ideal. WMI seem very much over-kill and I do not want to have to include extra .dlls in my installation package for the software if it can be avoided.

我还遇到了 SqlDataSourceEnumerator 类,该类记录在此处

I have also come accross the SqlDataSourceEnumerator Class documented here

// Retrieve the enumerator instance and then the data.
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();

将可用的连接转储到 DataTable 中.但是,返回所有可用的连接似乎存在固有的问题:

which dumps the available connection into a DataTable. However, there seems to be inherent problems with returning all the available connections:

"All of the available servers may or may not be listed. The list can vary depending on 
 factors such as timeouts and network traffic. This can cause the list to be different 
 on two consecutive calls." - MSDN.

必须有一套解决该问题的方法.说我有以下 SqlConnection 字符串:

There has to be a set way of dealing with this problem. Say I have the following SqlConnection string:

Data Source=localhost;Initial Catalog=MyDB;Integrated Security=True;Connection Timeout = 0

作为有效的 我可以使用什么(这很关键),以检查所选实例('localhost'[默认实例]或'SomeInstanceName')是否正在运行?

what can I use as an efficient (this is crucial) check as to whether the selected instance ('localhost' [the default instance] or 'SomeInstanceName') is running?

感谢您的时间.

您可以将连接超时更改为更短的时间,但是从本质上讲,它知道服务器不存在的唯一方法是超时.

You can change the connection timeout to be a shorter period, but essentially, the only way it knows that a server isn't there, is from a timeout.