C# 如何在win CF中结束线程

C# 如何在win CF中结束线程,c#,windows-mobile,compact-framework,C#,Windows Mobile,Compact Framework,windowsmobile5;紧凑的框架和与c#和线程相关的新手 我想从我自己的网站下载大文件(几个meg);使用GPRS可能需要一段时间。我想显示一个进度条,并允许一个取消下载的选项 我有一个叫做FileDownload的类,并创建了它的一个实例;给它一个url和保存位置,然后: MyFileDownLoader.Changed += new FileDownLoader.ChangedEventHandler(InvokeProgressBar); BGDownload = new Thr

windowsmobile5;紧凑的框架和与c#和线程相关的新手

我想从我自己的网站下载大文件(几个meg);使用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);
我用于下载的代码是基于

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

如果我再次尝试下载,有时会正常工作,有时会出现nullreference异常(仍在尝试跟踪)

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

是吗

我想您应该将线程安全添加到此操作中

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

希望这有帮助

谢谢,;这有点帮助;进一步调试表明,关闭流可能需要很长时间;这就是造成延误的原因
public void Cancel()
        {
            lock (this)
            {
                CancelRequest = true;
            }
        }