让程序连接错误的服务器,在连接数据库的过程中,整个程序好像死了一样,等到timeout以后再抛出异常。
我想要知道怎么能让程序在连接数据库的过程中也能正常响应其他操作。
刚看到有帖子说用异步连接可以解决、请高手指点

解决方案 »

  1.   

    可以使用异步委托或多线程。
    示例。。
            private void button1_Click(object sender, EventArgs e)
            {
                Thread th1 = new Thread(new ThreadStart(this.geting));
                th1.Start();
                Thread.Sleep(0);
               
            }
            private void geting()
            {
                    using sqlconnection...等其它操作
            }
      

  2.   

    再说清楚一点。
    程序开始 → 初始化连接字符串,连接数据库(SqlConnection.open())→进行其他操作
    问题就是:当连接数据库的时候,也就是执行中间那一步的时候,程序就会阻塞在那里,一直到连接数据库成功或者抛出异常。
    怎么才能让程序在执行第二步的时候不用阻塞在那里。
      

  3.   

    已经很详细了啊。。这里是SQL版,再贴C#代码,老大会有意见的。。如:你原先的代码:        private void button1_Click(object sender, EventArgs e)
            {
                using (SqlConnection conn = new SqlConnection("server=(local);uid=sa;pwd=******;database=temp"))
                {
                    
                    conn.Open();                conn.Close();
                }
               
            }
    点击后会假死,如果使用线程,代码如下
            private void button1_Click(object sender, EventArgs e)
            {
                Thread th1 = new Thread(new ThreadStart(this.geting));
                th1.Start();
                Thread.Sleep(0);
               
            }
            private void geting()
            {
                 using (SqlConnection conn = new SqlConnection("server=(local);uid=sa;pwd=ThinkPad;database=temp"))
                {                conn.Open();                conn.Close();
                    messageBox.show("啊哦,我执行完了!!");
                }
            }这样,你的程序就不会假死了。执行完后,可以回调,但回调函数必须委托。。
    比如:        delegate void SetvalueCallback(int value);
            private void settext(int value)
            {
                if (this.richTextBox1.InvokeRequired)
                {
                    SetvalueCallback d = new SetvalueCallback(settext);
                    this.Invoke(d, new object[] { value });
                }
                else
                {
                    this.richTextBox1.Text += value.ToString() + "-";
                    
                }
            }