0

我需要制作一个停止下载文件的按钮。例如,我点击了 1 次下载开始,第二次点击停止。

        private static async void Download()
    {
        foreach (string fileName in fileList)
        {

            string localDir = AppDomain.CurrentDomain.BaseDirectory;
            localDir.Substring(0, localDir.Length - 1);
            localDir += fileName;
            long fileSize = await ftp.GetFileSizeAsync(fileName);
            fileSize /= 1024;
            form.progressBar1.Maximum = (int)fileSize;
            var token = new CancellationToken();

            Progress<FtpProgress> progress = new Progress<FtpProgress>(async loadedFile =>
            {
                if (loadedFile.Progress == 100)
                {
                    form.progressBar1.Value = 0;
                }
                else
                {
                    int x = (int)fileSize * Convert.ToInt32(loadedFile.Progress) / 100;
                    string value = loadedFile.TransferSpeedToString();
                    form.label1.Text = "Connection Speed: \n" + value;

                    form.progressBar1.Value = x;

                }
            });
            await ftp.DownloadFileAsync(localDir, fileName, FtpLocalExists.Skip, FluentFTP.FtpVerify.Retry, progress, token);
        }
    }
4

1 回答 1

0

首先,您不直接创建 a CancellationToken,而是创建 aCancellationTokenSource并获取它的Token

也就是说,你可以想象使用那个令牌,来允许取消操作。你可以这样做:

//At class level
CancellationTokenSource cancel = null;

private static async void Download()
{

    if(cancel != null)
    {
        cancel.Cancel();
        cancel.Dispose();
        cancel = null;
        return;
    }

    cancel = new CancellationTokenSource();

    foreach (string fileName in fileList)
    {

        string localDir = AppDomain.CurrentDomain.BaseDirectory;
        localDir.Substring(0, localDir.Length - 1);
        localDir += fileName;
        long fileSize = await ftp.GetFileSizeAsync(fileName);
        fileSize /= 1024;
        form.progressBar1.Maximum = (int)fileSize;

        Progress<FtpProgress> progress = new Progress<FtpProgress>(async loadedFile =>
        {
            if (loadedFile.Progress == 100)
            {
                form.progressBar1.Value = 0;
                cancel.Dispose();
                cancel = null;
            }
            else
            {
                int x = (int)fileSize * Convert.ToInt32(loadedFile.Progress) / 100;
                string value = loadedFile.TransferSpeedToString();
                form.label1.Text = "Connection Speed: \n" + value;

                form.progressBar1.Value = x;

            }
        });


        try
        {

            await ftp.DownloadFileAsync(localDir, fileName, FtpLocalExists.Skip, FluentFTP.FtpVerify.Retry, progress, cancel.Token);

        }
        catch
        { 
           //When the download is cancelled will throw an exception
           //you can create a more specific handler
           cancel.Dispose();
           cancel = null;
        }
    }
}
于 2020-06-14T17:01:53.103 回答