小鸟慢飞

博客园 首页 联系 订阅 管理
View Code
 1         var alive = true;
 2         string error = null;
 3         var success = false;
 4 
 5         // ReSharper disable AccessToModifiedClosure
 6         // ReSharper disable UseObjectOrCollectionInitializer
 7         var thread = new Thread(() =>
 8                                     {
 9                                         try
10                                         {
11                                             var connection = new SqlConnection(connectionString);
12                                             connection.Open();
13                                             connection.Close();
14 
15                                             if (alive)
16                                                 success = true;
17                                         }
18                                         catch (SqlException ex)
19                                         {
20                                             if (alive)
21                                                 error = ex.Message;
22                                         }
23                                         catch (ThreadAbortException)
24                                         {
25                                         }
26                                         finally
27                                         {
28                                             if (connection.State == ConnectionState.Open)
29                                                 connection.Close();
30                                         }
31                                     });
32         // ReSharper restore AccessToModifiedClosure
33         // ReSharper restore UseObjectOrCollectionInitializer
34         thread.IsBackground = true;
35         var sw = Stopwatch.StartNew();
36         thread.Start();
37 
38         var timeout = TimeSpan.FromSeconds(3);
39         while (sw.Elapsed < timeout)
40             thread.Join(TimeSpan.FromMilliseconds(200));
41         sw.Stop();
42 
43         if (!success)
44         {
45             alive = false;
46             throw new Exception(error ?? "Connection timeout, please check the connection string.");
47         }

 

posted on 2012-05-07 09:12  小鸟慢飞  阅读(2091)  评论(0编辑  收藏  举报