c# - 取消异步任务 C#

标签 c#

<分区>

我希望用户能够取消/中止由异步按钮调用的任务。我看过 CancellationTokens,但我真的不明白如何实现它。

“下载”按钮:

private async void dlSelected_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (dlDataGrid.SelectedIndex != -1)
            {
                object item = dlDataGrid.SelectedItem;
                string name = (dlDataGrid.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
                string dl = (dlDataGrid.SelectedCells[2].Column.GetCellContent(item) as TextBlock).Text;

                dlSelected.IsEnabled = false;
                refreshList.IsEnabled = false;
                dlPRing.IsActive = true;

                await DownloadFile2(name, dl, "./Data/Downloads/" + name);

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

“下载”任务:

private async Task DownloadFile2(string name, string url, string path)
    {

        //Set status label
        tbDLStatus.Text = "Downloading File...";

        var DLclient = new WebClient();
        DLclient.DownloadProgressChanged += (s, e) =>
        {
            //Set names for each property
            tbDLPercent.Text = e.ProgressPercentage + "%";
            tbFileName.Text = name;
            tbDir.Text = path;

            double progress = 0;
            if (e.ProgressPercentage > progress)
            {
                //Change value of progressbar to download
                pbProgress.Value = (e.ProgressPercentage / 100.0d);
                progress = e.ProgressPercentage;
            }
        };

        DLclient.DownloadFileCompleted += async (s, e) =>
        {
            if (e.Cancelled)
            {
                //Delete the file
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            else if (e.Error != null)
            {
                await this.ShowMessageAsync("Error!", "An error occured while attempting to download " + name + "! \n\nPlease check your internet connection and try again in a few minutes.",
                   MessageDialogStyle.Affirmative);

                //Delete the file
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            else
            {
                //Set for completed DL successfully.
                if (cbAutoRun.IsChecked == true)
                {
                    try
                    {
                        Process.Start(tbDir.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }

                //Allow open file/folder
                btnOpen.IsEnabled = true;
                btnOpenFolder.IsEnabled = true;
            }

            dlSelected.IsEnabled = true;
            pbProgress.Value = 0;
            tbDLStatus.Text = "Finished Downloading";
            dlPRing.IsActive = false;
        };

        await DLclient.DownloadFileTaskAsync((url), path);
        DLclient.Dispose();
    }

所以我的问题是,如果我正在下载一个大文件并且我想通过一个按钮取消它,我该怎么做呢?

谢谢,

最佳答案

无法从外部取消任意任务。

幸运的是,WebClient 允许取消(虽然出于某种原因,它并没有像它应该的那样简单地采用 CancellationToken):只需调用 WebClient.CancelAsync () 每当您想取消挂起的异步操作时。

如果您想使用 CancellationToken 包装此功能,您可以这样做:

Task DownloadFileTaskAsync(this WebClient client, string address, string filename, 
                           CancellationToken token)
{
  token.Register(() => client.CancelAsync());

  return client.DownloadFileTaskAsync(address, filename);
}

关于c# - 取消异步任务 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31428580/

相关文章:

c# - 从另一个函数调用 RowDataBound

c# - 获取进程 C# 中当前加载的 DLL 列表

c# - ASP.NET GridView 第二个标题行跨越主标题行

c# - 如何清空 List<T>?

c# - 从不同 View 修改HamburgerButtonVisibility属性

c# - 有没有办法使用 Quaternion.FromToRotation 来支持使用一个轴?

c# - 我可以将 IFormatProvider 与 WPF 绑定(bind)一起使用到自定义类型吗?

c# 填充 datagridview 非常慢

c# - mvc4 - db.SaveChanges() - 十进制值超出范围

c# - 创建由数据库驱动的对象来填充 TreeView - 非常慢