暂停下载线程

时间:2011-08-14 23:07:06

标签: c# multithreading suspend

我在c#中编写了一个非常简单的批量下载程序,它读取要下载的URL的.txt文件。我已经设置了一个全局线程和委托来更新GUI,按下“开始”按钮创建并启动该线程。我想要做的是有一个“暂停”按钮,让我可以暂停下载,直到我点击“恢复”按钮。我该怎么做?

相关代码:

private Thread thr;
private delegate void UpdateProgressCallback(int curFile);

private void Begin_btn_Click(object sender, EventArgs e)
{
   thr = new Thread(Download);
   thr.Start();
}

private void Pause_btn_Click(object sender, EventArgs e)
{
   Pause_btn.Visible = false;
   Resume_btn.Visible = true;
   //{PAUSE THREAD thr}
}

private void Resume_btn_Click(object sender, Eventargs e)
{
   Pause_btn.Visible = true;
   Resume_btn.Visible = false;
   //{RESUME THREAD thr}
}

public void Download()
{
   //Download code goes here
}

显然,我不是在使用工人,我真的不希望除非你能告诉我如何让它工作(我真的不懂工人)。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

如果您使用System.Net.WebClient.DownloadFile()System.Net.WebClient.DownloadFileAsync()方法,则无法暂停下载。这些方法之间的区别在于后一种方法将启动异步下载,因此如果使用此方法,则无需自己创建单独的线程。不幸的是,使用任一方法执行的下载都无法暂停或恢复。

您需要使用System.Net.HttpWebRequest。尝试这样的事情:

class Downloader
{
    private const int chunkSize = 1024;
    private bool doDownload = true;

    private string url;
    private string filename;

    private Thread downloadThread;

    public long FileSize
    {
        get;
        private set;
    }
    public long Progress
    {
        get;
        private set;
    }

    public Downloader(string Url, string Filename)
    {
        this.url = Url;
        this.filename = Filename;
    }

    public void StartDownload()
    {
        Progress = 0;
        FileSize = 0;
        commenceDownload();
    }

    public void PauseDownload()
    {
        doDownload = false;
        downloadThread.Join();
    }

    public void ResumeDownload()
    {
        doDownload = true;
        commenceDownload();
    }

    private void commenceDownload()
    {
        downloadThread = new Thread(downloadWorker);
        downloadThread.Start();
    }

    public void downloadWorker()
    {
        // Creates an HttpWebRequest with the specified URL. 
        HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);

        FileMode filemode;
        // For download resume
        if (Progress == 0)
        {
            filemode = FileMode.CreateNew;
        }
        else
        {
            filemode = FileMode.Append;
            myHttpWebRequest.AddRange(Progress);
        }

        // Set up a filestream to write the file
        // Sends the HttpWebRequest and waits for the response.         
        using (FileStream fs = new FileStream(filename, filemode))
        using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse())
        {
            // Gets the stream associated with the response.
            Stream receiveStream = myHttpWebResponse.GetResponseStream();

            FileSize = myHttpWebResponse.ContentLength;

            byte[] read = new byte[chunkSize];
            int count;


            while ((count = receiveStream.Read(read, 0, chunkSize)) > 0 && doDownload)
            {
                fs.Write(read, 0, count);
                count = receiveStream.Read(read, 0, chunkSize);

                Progress += count;
            }
        }
    }
}

我在MSDN上使用了HttpWebRequest.GetResponse页面中的一些代码。

不是在Pause上停止线程并在Resume上启动一个新线程,您也可以更改while循环,等待下载恢复如下:

            while ((count = receiveStream.Read(read, 0, chunkSize)) > 0)
            {
                fs.Write(read, 0, count);
                count = receiveStream.Read(read, 0, chunkSize);

                Progress += count;

                while(!doDownload)
                    System.Threading.Thread.Sleep(100);
            }

最重要的是,您可以重新使用相同的线程。缺点是连接可能会超时并关闭。在后一种情况下,您需要检测并重新连接。

您可能还想在完成下载时添加事件。