线程中的委托不能及时更新UI的有关问题

线程中的委托不能及时更新UI的问题
本帖最后由 hardtoup 于 2014-07-04 15:41:05 编辑
感觉执行到fileTransFinishedEvent.WaitOne(); 阻塞了。简要代码如下:
 public class ProtocolFileSend
{
    public delegate void ShowProcessHandle(int percent, string message);
    private event ShowProcessHandle sftpSendProgressEvent;
    public event ShowProcessHandle SftpSendProgressEvent
    {
            add
            {
                sftpSendProgressEvent += value;
            }
            remove
            {
                sftpSendProgressEvent -= value;
            }
    }
    ManualResetEvent fileTransFinishedEvent = new ManualResetEvent(false);
    public bool TransFile(string fileName)
    {           
   fileTransFinishedEvent.Reset();
   ThreadPool.QueueUserWorkItem(new WaitCallback(TransFileInner), fileName);
   fileTransFinishedEvent.WaitOne(); 
    }  

    private void TransFileInner(object oFileName)
    {                
        try
 {
             bool sendRes = SendFile(fileName.ToString());//该函数耗时较长,里面会调用SftpSendProgressEvent汇报进度
 }
         catch(Exception ex)
         {
             
         }
           fileTransFinishedEvent.Set();
    }
}
public class MainFrm:Form
{
    public void button1_click()
    {
ProtocolFileSend proSFTP = new ProtocolFileSend(remoteIP, remotePort);
proSFTP.SftpSendProgressEvent += new ProtocolFileSend.ShowProcessHandle(proSFTP_SftpSendProgress);
        bool res = proSFTP.TransFile(fileName);
    }
    void proSFTP_SftpSendProgress(int percent, string message)
    {
        UpdateProgressBar(percent, message);//写日志发现 该行确实执行了,但是是在 SendFile最后阶段才执行的。所在在等待过程中进度条没有更新,只是最后快结束的时候进度条刷新了一下。
    }
}

请各位帮忙看下如何处理比较好,谢谢!
------解决方案--------------------
Quote: 引用:


    public bool TransFile(string fileName)
     {           
        fileTransFinishedEvent.Reset();
        ThreadPool.QueueUserWorkItem(new WaitCallback(TransFileInner), fileName);  // 启动工作线程
        fileTransFinishedEvent.WaitOne(); // 等待工作线程结束
     }
  
...
quote]

你的代码虽然UI启动了一个线程,但UI却阻塞在那里等待线程结束。跟同步调用没什么区别。
解决方法就是UI不要阻塞等待。你可以把有关fileTransFinishedEvent的代码行全部去掉就可以观察到结果。

一般来说,进度事件(SftpSendProgressEvent )应该汇报结束。fileTransFinishedEvent有些冗余。

------解决方案--------------------
fileTransFinishedEvent.WaitOne(); 去掉
既然是想异步执行,就别等了啊
------解决方案--------------------
线程和异步是两个不同的概念。