2011-09-02 82 views
0

Windows mobile 5;紧凑的框架和相对新手到C#和线程。如何在win中结束线程CF

我想从我自己的网站下载大文件(几兆)作为GPRS,这可能需要一段时间。我想显示一个进度条,并允许一个选项取消下载。

我有一个名为FileDownload的类并创建它的一个实例;给它一个URL和保存位置然后:

MyFileDownLoader.Changed += new FileDownLoader.ChangedEventHandler(InvokeProgressBar); 

BGDownload = new Thread(new ThreadStart(MyFileDownLoader.DownloadFile)); 
BGDownload.Start(); 

因此,我创建一个事件处理程序更新进度条,并启动线程。这工作正常。

我有一个取消按钮曰:

MyFileDownLoader.Changed -= InvokeProgressBar; 
MyFileDownLoader.Cancel(); 
BGDownload.Join(); 
lblPercentage.Text = CurPercentage + " Cancelled"; // CurPercentage is a string 
lblPercentage.Refresh(); 
btnUpdate.Enabled = true; 

FileDownload类中的主要部分是:

public void Cancel() 
{ 
    CancelRequest = true; 
} 

在方法下载文件:

... 
success = false; 
try { 
//loop until no data is returned 
while ((bytesRead = responseStream.Read(buffer, 0, maxRead)) > 0) 
{ 
    _totalBytesRead += bytesRead; 
    BytesChanged(_totalBytesRead); 
    fileStream.Write(buffer, 0, bytesRead); 
    if (CancelRequest) 
     break; 
} 

if (!CancelRequest) 
    success = true; 
} 
catch 
{ 
    success = false; 
    // other error handling code 
} 
finally 
{ 
    if (null != responseStream) 
     responseStream.Close(); 
    if (null != response) 
     response.Close(); 
    if (null != fileStream) 
     fileStream.Close(); 
} 

// if part of the file was written and the transfer failed, delete the partial file 
if (!success && File.Exists(destination)) 
    File.Delete(destination); 

的我正在使用的代码是基于http://spitzkoff.com/craig/?p=24

我得到的问题是当我取消时,下载立即停止,但完成加入过程可能需要5秒左右的时间。这通过在加入后更新lblPercentage.Text来证明。

如果我然后尝试再次下载,它有时会起作用,有时候我会得到一个nullreference异常(仍然试图跟踪它)。

我想我在取消线程的方法中做错了什么。

我是吗?

回答

1
public void Cancel() 
    { 
     CancelRequest = true; 
    } 

我想你应该添加线程安全的这个动作。

public void Cancel() 
     { 
      lock (this) 
      { 
       CancelRequest = true; 
      } 
     } 

希望得到这个帮助!

+0

谢谢;那帮助了一个小孩;进一步调试发现,关闭流可能需要很长时间;这就是造成延误的原因 – andrew