如何结束win CF中的线程

本文关键字:CF 线程 win 何结束 结束 | 更新日期: 2023-09-27 18:07:33

Windows mobile 5;紧凑的框架和对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);

我用于下载的代码基于http://spitzkoff.com/craig/?p=24

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

如果我再次尝试下载,有时它会起作用,有时我会得到一个nullreference异常(仍在努力追踪(。

我认为我在取消线程的方法上做错了什么。

我是吗?

如何结束win CF中的线程

public void Cancel()
    {
        CancelRequest = true;
    }

我想您应该为这个操作添加线程安全。

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

希望得到帮助!