惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
博客园_首页
H
Help Net Security
WordPress大学
WordPress大学
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
B
Blog
I
InfoQ
SecWiki News
SecWiki News
T
Tailwind CSS Blog
Spread Privacy
Spread Privacy
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Vulnerabilities – Threatpost
N
Netflix TechBlog - Medium
P
Palo Alto Networks Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Vercel News
Vercel News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
K
Kaspersky official blog
M
MIT News - Artificial intelligence
S
Schneier on Security
T
Threat Research - Cisco Blogs
F
Fortinet All Blogs
Cyberwarzone
Cyberwarzone
Scott Helme
Scott Helme
aimingoo的专栏
aimingoo的专栏
Martin Fowler
Martin Fowler
MyScale Blog
MyScale Blog
The Cloudflare Blog
Recent Announcements
Recent Announcements
Security Latest
Security Latest
G
GRAHAM CLULEY
IT之家
IT之家
Y
Y Combinator Blog
The Last Watchdog
The Last Watchdog
腾讯CDC
Google DeepMind News
Google DeepMind News
V
V2EX
S
Securelist
TaoSecurity Blog
TaoSecurity Blog
B
Blog RSS Feed
S
SegmentFault 最新的问题
博客园 - 叶小钗
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
Project Zero
Project Zero
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
F
Full Disclosure

博客园 - deerchao

Unity 在平面上播放含透明通道的视频(Play video with alpha channel on plane in unity) 域名迁移 错误721 -- 在虚拟机中连接VPN, 显示验证用户名和密码之后出错 - deerchao 繁体编码文本文件转换为简体编码的工具 生成VB多行字符串常量的工具 64位虚拟机Guest OS安装错误:0xC0000225 在64bit Win2008上运行Asp + Access网站 工具: 删除Visual Studio项目中文件链接,并把原文件复制到相应的目录 一个代表年月的类YearMonth Tip: Resharper 中 "Unknown Comment" 问题的解决办法 Struct与赋值 Tips 奇怪的TreeView(WinForms)自动选中问题 From C# to VB MapPath的反函数(Reversing MapPath) A fast object clone class - using Expression.Compile() jQuery.combobox, 给文本框添加下拉选项的轻量级插件 CDTray, 打开,关闭光驱的系统托盘程序 jQuery.Excel, 使用Ctrl+方向键/Home/End在input表格中移动
测试ConnectionString是否能连接上数据库服务器
deerchao · 2009-11-28 · via 博客园 - deerchao

比如你要连接一个Sql Server服务器,你有一个connection string, 但是不知道是否是正确的,你可以这样:

var connection = new SqlConnection(connectionString);

connection.Open();

connection.Close();

如果整个过程中没有异常抛出,则说明connectionString是指向一个Sql Server的服务器。但是,如果connectionString里边的Data Source(或者Server)的值是错的,就要等很久——大约30秒——才能从connection.Open()这一句抛出异常。有没有办法让这个过程快一点呢?

你可以试着在connectionString里添加上: "Connection Timeout=3",这指示超时时间为3秒。但是实际上效果还是一样的,异常仍然要在30秒之后才会抛出。

你也可以试着用另一个线程去连接服务器,主线程在若干秒后调用该线程的 Abort()方法,但是,实验效果是行不通,因为那个线程在connection.Open()里根本出不来,无法被Abort掉。

最后,我的解决方法还是采用后台线程,只不过如果到期尚未成功,那就当做失败,然后把它扔到一边去,不再理它了:

            //采用后台线程来连接数据库,以便在服务器输入错误的情况下,不用等待很长的时间才能得到一个错误提示
            string error = null;
            var success = false;

            // ReSharper disable AccessToModifiedClosure
            // ReSharper disable UseObjectOrCollectionInitializer
            var thread = new Thread(() =>
                                        {
                                            try
                                            {
                                                connection.Open();
                                                connection.Close();

                                                success = true;
                                            }
                                            catch (SqlException ex)
                                            {
                                                error = ex.Message;
                                            }
                                            finally
                                            {
                                                if (connection.State == ConnectionState.Open)
                                                    connection.Close();
                                            }
                                        });
            // ReSharper restore AccessToModifiedClosure
            // ReSharper restore UseObjectOrCollectionInitializer
            thread.IsBackground = true;
            var sw = Stopwatch.StartNew();
            thread.Start();

            var timeout = TimeSpan.FromSeconds(3);
            while (sw.Elapsed < timeout)
                thread.Join(TimeSpan.FromMilliseconds(200));
            sw.Stop();

            if (!success)
            {
                throw new Exception(error ?? "连接数据库超时,请检查输入的服务器是否正确。");
            }