如何在胜利CF中结束线程

时间:2011-09-02 01:06:54

标签: c# windows-mobile compact-framework

Windows mobile 5;紧凑的框架和c#和线程的相对新手。

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

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

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 个答案:

答案 0 :(得分:1)

public void Cancel()
    {
        CancelRequest = true;
    }

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

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

希望这有帮助!