楼上的哥哥,我试过了,看这个代码片段:
 MessageBox.Show("将要进行连接");
 LogOnWindow.MyCon.Open();
 LogOnWindow.MyCon.Close();
 MessageBox.Show("Open执行完毕");
这段代码我测试运行的时候,将要进行连接会显示出来。然后因为我把服务器关了,所以Open这个语句会一直在连,一直呆到三十秒,连接失败,下面的语句都没有执行,抛出了一个异常。
所以我想Close这个语句是在连接已Open的时候才用的。。如果都没有Open,根本没用啊?停不了啊

解决方案 »

  1.   

    其实偶知道Open这个语句应该作为一个单独的线程来运行就好了,可是我不会。。谁给给我个例子看看就好了。
      

  2.   


      private void FormTCPIPProperty_Load(object sender, EventArgs e)
            {
                MainForm.UIControler.frmtcpip = this;            ipAddressControlIP_address.Enabled = false;
                ipAddressControlDefault_gateway.Enabled = false;
                ipAddressControlPreferred_DNS_server.Enabled = false;            radioButtonObtainIP.Checked = true;
                radioButtonObtainDNS.Checked = true;
                radioButtonFollowingIP.Checked = false;
                radioButtonFollowingDNS.Checked = false;            //ipAddressControlIP_address.Text = PlayerObject.DeviceIPAddress;
                MainForm.UIControler.GetPlayerNetInfo(PlayerObject);
                 
                this.buttonRefreshIP.Enabled = false;
                            tt = new System.Timers.Timer(5000);
                tt.Elapsed += new System.Timers.ElapsedEventHandler(tt_ElapsedIPRefresh);
                tt.Enabled = true; 
                
                
            }
            private void tt_ElapsedIPRefresh(object sender, System.Timers.ElapsedEventArgs e)
            { 
                tt.Stop();//先停止计时器
                if (buttonRefreshIP.Enabled == false)
                {
                    System.Windows.Forms.MessageBox.Show("Get infomation time out.(获取IP地址信息超时。)");
                    this.RefreshIPButtonEnable(true);
                    tt.Close();
                }
            }
    这代码意思是刷新界面获得IP返回值,返回成功就跨线程buttonRefreshIP.Enabled = true;所以我在界面判断buttonRefreshIP.Enabled;
    buttonRefreshIP.Enabled = true就是成功,5秒内buttonRefreshIP.Enabled = false;就超时。这是我项目的超时机制,能帮你不?
      

  3.   

    我弄了一上午,基本也是按这个样子来的,而且我还看了看多线程,可是。不行。。我想我写的线程关系有点不太对。。
    我是这样弄的,先是在我的主线程里设好计时器并启动。然后我开个新线程,在这个线程里有我的Open语句。然后我的计时器等待7秒后就提示超时。结果运行还是像死了一样。。
    我的代码是这样的。
          private void LogOnButton_Click(object sender, EventArgs e)
            {
                this.MessageLabel.Text = "";
                if (this.NameBox.Text == "")
                {
                    this.MessageLabel.Text = "请输入用户名!";//提示输入用户名
                    
                }
                else
                {//输入了用户名则开始连接数据库
                    //连接字符串
                    this.connectString =global::ScientificResearchSystem.Properties.Settings.Default.TestBaseConnectionString;
                    //this.connectString = "Data Source=192.168.110.12;Integrated Security=false;Initial Catalog=TestBase;User ID=sa;Password=fengye";
                    LogOnWindow.MyCon = new System.Data.SqlClient.SqlConnection(this.connectString);   
            //将进行多线程的测试
                    System.Threading.ThreadStart connectStart = new System.Threading.ThreadStart(beginConnect);
                    connectThread = new System.Threading.Thread(connectStart);
                    
                    connectThread.Name = "connectThread";
                   // MessageBox.Show("计时器启动");
                    this.timer1.Start();
                  //  MessageBox.Show("coonectThread线程开始");
                   
                    connectThread.Start();//开始连接数据库
                  //  MessageBox.Show("coonectThread线程开始,主线程暂停");
                    connectThread.Join();//暂停了主线程,只有当此线程结束才回来              
                    /* 
                   try
                    {
                        string findstr = "SELECT * FROM [login] WHERE uNo='" + LogOnWindow.userID + "'AND uPassword='" + LogOnWindow.Password  + "'AND uPower=3";
                        SqlCommand logonCommand = new SqlCommand(findstr, LogOnWindow.MyCon);
                        SqlDataReader logonReader;
                        //MessageBox.Show("将要进行连接");
                        LogOnWindow.MyCon.Open();
                        LogOnWindow.MyCon.Close();
                       // MessageBox.Show("Open执行完毕");
                        logonReader = logonCommand.ExecuteReader();
                    
                        if (!logonReader.HasRows)
                        {
                            this.MessageLabel.Text = "用户名或密码错误!";
                            return;
                        }
                      
                            
                    }
                    catch (SqlException SqlEx)
                    {
                       // MessageBox.Show(SqlEx.Message+";"+SqlEx .Errors+";"+SqlEx .Number);
                        if (SqlEx .Number ==17142)
                        {
                            this.MessageLabel.Text = "数据库暂停运行中!";//这种情况下连接会断开
                            MessageBox.Show(LogOnWindow.MyCon.State.ToString());
                            return;
                        }
                        else
                        {
                            this.MessageLabel.Text = "连接数据库失败!";
                            MessageBox.Show(LogOnWindow.MyCon.State.ToString());
                            return;
                        }
                    }*/
                    if (connectOK)
                    {//一直等待到连接上了才会跳出此循环或计时到了一切复原
                        //}                    LogOnWindow.MyCon.Close();
                        this.Hide();
                        this.mainWindow = new MainWindow();
                        mainWindow.ShowDialog();//into the mainWindow
                    }            }
                                          
            }
            private void beginConnect()
            {
                try
                {
                    string findstr = "SELECT * FROM [login] WHERE uNo='" + LogOnWindow.userID + "'AND uPassword='" + LogOnWindow.Password + "'AND uPower=3";
                    SqlCommand logonCommand = new SqlCommand(findstr, LogOnWindow.MyCon);
                    SqlDataReader logonReader;
                    //MessageBox.Show("将要进行连接");
                    LogOnWindow.MyCon.Open();//将此句移到一个单独的线程中去
                    //System.Threading.ThreadStart openIt = new System.Threading.ThreadStart(LogOnWindow .MyCon .Open);
                  //  System.Threading.Thread openThread = new System.Threading.Thread(openIt);
                   // openThread.Name = "openThread";
                   // openThread.Start();
                   // MessageBox.Show("connectThread线程暂停,开始openThread线程");
                   // openThread.Join();//暂停coonectThread
                    //LogOnWindow.MyCon.Close();
                    // MessageBox.Show("Open执行完毕");
                    logonReader = logonCommand.ExecuteReader();                if (!logonReader.HasRows)
                    {
                        this.MessageLabel.Text = "用户名或密码错误!";
                        return;
                    }
                    else
                    {
                        connectOK = true;
                    }
                }
                catch (System.Exception)
                {
                    //不用做什么
                }
                      
            }        private void timer1_ElapsedIPRefresh(object sender, EventArgs e)
            {
                //该事件的发生说明Open并没有成功
                this.timer1.Stop();
                if (!connectOK)
                {
                    this.MessageLabel.Text = "连接数据库超时!";
                    timer1.Close();
                }
               
               // this.connectThread.Suspend();
              //  this.connectThread.Interrupt();
            }       
        }
    }
      

  4.   

    弄错了个地方,呵呵。我忘了注掉了。这个
               connectThread.Join();//暂停了主线程,只有当此线程结束才回来 
    把它注掉好像行了耶。我再试试。
      

  5.   

    可以了,呵呵。。我现在代码这个样子。
      private void LogOnButton_Click(object sender, EventArgs e)
            {
                this.LogOnButton.Enabled = false;
                this.MessageLabel.Text = "";
                if (this.NameBox.Text == "")
                {
                    this.MessageLabel.Text = "请输入用户名!";//提示输入用户名
                    
                }
                else
                {//输入了用户名则开始连接数据库
                    //连接字符串
                    this.connectString =global::ScientificResearchSystem.Properties.Settings.Default.TestBaseConnectionString;
                    //this.connectString = "Data Source=192.168.110.12;Integrated Security=false;Initial Catalog=TestBase;User ID=sa;Password=fengye";
                    LogOnWindow.MyCon = new System.Data.SqlClient.SqlConnection(this.connectString);   
            //将进行多线程的测试
                    System.Threading.ThreadStart connectStart = new System.Threading.ThreadStart(beginConnect);
                    connectThread = new System.Threading.Thread(connectStart);
                    
                    connectThread.Name = "connectThread";
                   // MessageBox.Show("计时器启动");
                    timer1.Enabled = true;
                    this.timer1.Start();
                  //  MessageBox.Show("coonectThread线程开始");
                   
                    connectThread.Start();//开始连接数据库      
                    while (!connectOK)
                    {
                        //一直等待到连接上了也验证完了才会跳出此循环或计时到了一切复原
                    }                LogOnWindow.MyCon.Close();
                    this.Hide();
                    this.mainWindow = new MainWindow();
                    mainWindow.ShowDialog();//into the mainWindow
                             }
                                          
            }
            private void beginConnect()
            {
                try
                {
                    string findstr = "SELECT * FROM [login] WHERE uNo='" + LogOnWindow.userID + "'AND uPassword='" + LogOnWindow.Password + "'AND uPower=3";
                    SqlCommand logonCommand = new SqlCommand(findstr, LogOnWindow.MyCon);
                    SqlDataReader logonReader;
                    //MessageBox.Show("将要进行连接");
                    LogOnWindow.MyCon.Open();//
                 
                    logonReader = logonCommand.ExecuteReader();                if (!logonReader.HasRows)
                    {
                        this.MessageLabel.Text = "用户名或密码错误!";
                        LogOnWindow.MyCon.Close();
                        timer1.Stop();
                        timer1.Close();
                        this.LogOnButton.Enabled = true;
                       // return;
                    }
                    else
                    {
                        connectOK = true;
                    }
                }
                catch (System.Exception)
                {
                    //不用做什么
                }
                      
            }        private void timer1_ElapsedIPRefresh(object sender, EventArgs e)
            {
                //该事件的发生说明Open并没有成功
                this.timer1.Stop();
                if (!connectOK)
                {
                    this.MessageLabel.Text = "连接数据库超时!";
                    timer1.Close();
                    this.LogOnButton.Enabled = true;
                }
            }       
        }
    }
    不过有个新的问题,就是如果我的用户账号或密码验证不通过,登陆界面又像死了一样了。。我看了任务管理器发现我的程序和虚拟机各占了50%左右的CPU,它们一共占了近90%。。我想是我这段代码有点问题?
     logonReader = logonCommand.ExecuteReader();                if (!logonReader.HasRows)
                    {
                        this.MessageLabel.Text = "用户名或密码错误!";
                        LogOnWindow.MyCon.Close();
                        timer1.Stop();
                        timer1.Close();
                        this.LogOnButton.Enabled = true;
                       // return;
                    }
                    else
                    {
                        connectOK = true;
                    }
    是这里有问题吗?怎么改哩?
      

  6.   

                    while (!connectOK)
                    {
                        //一直等待到连接上了也验证完了才会跳出此循环或计时到了一切复原
                    }这个循环的问题
    当验证失败时有没有要求用户重新输入用户名密码?
      

  7.   

    我崩溃了。。本来我以为都好了。我把代码改成了下面这个样子。
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Data.SqlClient;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Configuration;namespace ScientificResearchSystem
    {
        public partial class LogOnWindow : Form
        {
            private static string userID;//保存用户名
            private static string password;//保存密码
            private string connectString;//保存数据库连接字符串
            private static SqlConnection myCon;//公共连接对象,该连接一直保持到程序结束
            public static string Password
            {
                get
                {
                    return password;
                }
                set
                {
                    password = value;
                }
            }        public static string UserID
            {
                get
                {
                    return userID;
                }
                set
                {
                    userID = value;
                }
            }
            public static SqlConnection MyCon
            {
                get
                {
                    return myCon;
                }
                set
                {
                    myCon = value;
                }
            }        private MainWindow mainWindow;//declare a mainWindow
          
            public LogOnWindow()
            {
                InitializeComponent();
            }        private void Form1_Load(object sender, EventArgs e)
            {
                
            }        private void NameBox_TextChanged(object sender, EventArgs e)
            {
                LogOnWindow.userID =this.NameBox.Text.Trim();
            }        private void PasswordBox_TextChanged(object sender, EventArgs e)
            {
                LogOnWindow.password = this.PasswordBox.Text.Trim();
            }        private void LogOnButton_Click(object sender, EventArgs e)
            {
                this.LogOnButton.Enabled = false;
                this.MessageLabel.Text = "";
                if (this.NameBox.Text == "")
                {
                    this.MessageLabel.Text = "请输入用户名!";//提示输入用户名
                    this.LogOnButton.Enabled = true;                
                }
                else
                {//输入了用户名则开始连接数据库
                    //连接字符串
                    this.connectString =global::ScientificResearchSystem.Properties.Settings.Default.TestBaseConnectionString;
                    //this.connectString = "Data Source=192.168.110.12;Integrated Security=false;Initial Catalog=TestBase;User ID=sa;Password=fengye";
                    LogOnWindow.MyCon = new System.Data.SqlClient.SqlConnection(this.connectString);   
            //将进行多线程的测试
                    System.Threading.ThreadStart connectStart = new System.Threading.ThreadStart(beginConnect);
                    connectThread = new System.Threading.Thread(connectStart);
                    
                    connectThread.Name = "connectThread";
                   // MessageBox.Show("计时器启动");
                    timer1.Enabled = true;
                    this.timer1.Start();
                  //  MessageBox.Show("coonectThread线程开始");
                   
                    connectThread.Start();//开始连接数据库      
                 //   connectThread.Join();//这句不可以用。用了计时器就失效了                while (!connectOK)
                    {
                        //一直等待到连接上了才会跳出此循环或计时到了一切复原
                    }
                    if (passed == false)
                    {
                        this.MessageLabel.Text = "用户名或密码错误!";
                        this.connectOK = false;
                    }
                    //LogOnWindow.MyCon.Close();
                    else
                    {
                        this.Hide();
                        this.mainWindow = new MainWindow();
                        mainWindow.ShowDialog();//into the mainWindow
                    }            }
                                          
            }
            private void beginConnect()
            {
                try
                {
                    string findstr = "SELECT * FROM [login] WHERE uNo='" + LogOnWindow.userID + "'AND uPassword='" + LogOnWindow.Password + "'AND uPower=3";
                    SqlCommand logonCommand = new SqlCommand(findstr, LogOnWindow.MyCon);
                    SqlDataReader logonReader;
                    //MessageBox.Show("将要进行连接");
                    LogOnWindow.MyCon.Open();//               // MessageBox.Show("连接已成功了");
                    logonReader = logonCommand.ExecuteReader();                if (!logonReader.HasRows)
                    {
                        //MessageBox.Show("这里运行到了!");
                        this.passed = false;
                        this.connectOK = true;
                        //this.MessageLabel.Text = "用户名或密码错误!";
                        LogOnWindow.MyCon.Close();
                        timer1.Stop();
                        timer1.Close();
                        this.LogOnButton.Enabled = true;
                       // return;
                    }
                    else
                    {
                        passed = true;
                        connectOK = true;
                        LogOnWindow.MyCon.Close();
                        timer1.Stop();
                        timer1.Close();
                        this.LogOnButton.Enabled = true;
                    }
                }
                catch (System.Exception)
                {
                    //不用做什么
                }
                      
            }        private void timer1_ElapsedIPRefresh(object sender, EventArgs e)
            {
                //该事件的发生说明Open并没有成功
                
               if (!connectOK)
                {
                    this.timer1.Stop();
                   timer1.Close();
                    this.MessageLabel.Text = "连接数据库超时!";
                 
                    this.LogOnButton.Enabled = true;
                    connectOK = true;//这个语句使主线程能继续向下执行
                }
            }       
        }
    }
    本来我明明运行过的。都好了。验证也不卡了。可是呢。由于我们宿舍停了会儿电。幸好我有电池,再运行试了试正常就关机了,然后吃了个饭。回来开机发现扫了下盘,再运行竟然就不行了?
    而且我用我先前发的那个能正常提示数据库连接超时的代码竟然也不能运行了!!计时器好像不管用了一样。这是怎么回事啊!!运行我上面这个代码也是,验证是正常的,可是连接不上的时候又卡那儿了。计时器好像失效了?怎么回事啊。555.
    太郁闷了