桌面应用中,当向web请求资源是总是存在这样那样的问题,导致程序等待,在客户端看来是窗口"不刷新","没响应","反映很慢". 其实只要适当引入线程,用户体验会好很多.


HTTP://BLOG.CSDN.NET/CRABO/
注意:线程都设为全局变量,以便退出时正确的退出.

1)用户点击按钮,用户窗体线程与实际逻辑进程剥离
private void btnPoll_Click(object sender, System.EventArgs e)
  {
     //开始
      this.lblResult.Text="程序开始....";
       craboThread = new System.Threading.Thread(new System.Threading.ThreadStart(ReadDataDelegate));
       craboThread.Start();
  }

2)读取数据,并POST数据到远程服务器
private void ReadDataDelegate()
  {
   while(dataReader.Read())
  {
      //你从数据源中设置POST参数到文本框/全局变量中
        postThread= new System.Threading.Thread(new System.Threading.ThreadStart(PostDelegate));
        postThread.Start();
        postThread.Join(_waitSec*1000);// <=====等待POST正常结束
  }
}

3)提交数据(关键进程,导致程序响应慢)
private void PostDelegate()
  {
    try
     {
           //创建Web请求, 取得web响应....
     }
   #region Catch
   catch(System.Threading.ThreadAbortException e)
   {
    System.Threading.Thread.ResetAbort();
    return "服务器请求线程被中断..."+e.Message;
   }
   catch(Exception ex)
   {
    return "程序发生错误:"+ex.Message;
   }
   #endregion
}

4)确保程序正常退出
private void PollForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  {
   if(postThread!=null && postThread.IsAlive)
    postThread.Abort();
   if(rcraboThread!=null && craboThread.IsAlive)
    craboThread.Abort();
  }



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=547138

posted on 2007-08-05 18:32  Thunderdanky  阅读(234)  评论(0编辑  收藏  举报