ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 使用Command 对象进行异步操作

使用Command 对象进行异步操作

原创 Linux操作系统 作者:iDotNetSpace 时间:2008-09-28 13:31:44 0 删除 编辑

  在ado.net2.0发步这前,通过Command执行sql命令的线程必须等待执行结果.现在需要确保当存储过程在执行时,应用程序任能响应用户请求.
 
  下面我们来看一个最简单的实例:

 

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->        SqlConnection conn =new SqlConnection ("server=.\\sqlexpress;database=wtqtest;Integrated Security=sspi;");

        
private void button1_Click(object sender, EventArgs e)
        {
            
try
            {
               conn.Open();
                
string strCmd = "waitfor delay '00:00:05';select fname from mytable1";
                SqlCommand cmd 
= new SqlCommand(strCmd, conn);

                SqlDataReader dr 
= cmd.ExecuteReader();
                
while (dr.Read())
                {
                    
this.textBox1.Text += dr[0].ToString();
                }

            }
            
catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

 

//在这里,是连接的2005数据库,大家应该看到了此连接要沿时05秒钟,而在这05秒内你是什么也不能做的,你的应用程序会处于一种"卡死"状态.
       
        下面我们改一改 try 里的代码,并且在连接字符串中加上"Asynchronous Processing=true",其它代码不变:

 

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> try
            {
                conn.Open();
                
string strCmd = "waitfor delay '00:00:05';select fname from mytable1";
                SqlCommand cmd 
= new SqlCommand(strCmd, conn);

                IAsyncResult result 
= cmd.BeginExecuteReader();//当执行到这段代码时就开始开始执行sql语句了

                
while (!result.IsCompleted) //判断是否已经完成sql语句查询完成,如果没完成就可以执行其它代码
                {
                    MessageBox.Show(
"正在等待sql执行..!");//在这里可以添加异步代码
                }//在五秒钟的等待中,它将不断的显示这个对话框.表明程序并没有"卡死".
                 
                
//如果已经完成查询就可以把结果传给 dr 并用dr.Read()读取结果
                using (SqlDataReader dr = cmd.EndExecuteReader(result))
                {
                    
while (dr.Read())
                    {
                        
this.textBox1.Text += dr[0].ToString();
                    }
                }
                conn.Close();
            }

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-466022/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: SQL 中的统计应用
请登录后发表评论 登录
全部评论

注册时间:2008-01-04

  • 博文量
    2376
  • 访问量
    5765894