完整实例

  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;

    // Add a using directive and a reference for System.Net.Http.
    using System.Net.Http;

    // Add the following using directive.
    using System.Threading;

    namespace CancelAfterOneTask
    {
        public partial class MainWindow : Window
        {
            // Declare a System.Threading.CancellationTokenSource.
            CancellationTokenSource cts;

    public MainWindow()
            {
                InitializeComponent();
            }

    private async void startButton_Click(object sender, RoutedEventArgs e)
            {
                // Instantiate the CancellationTokenSource.
                cts = new CancellationTokenSource();

    resultsTextBox.Clear();

    try
                {
                    await AccessTheWebAsync(cts.Token);
                    resultsTextBox.Text += "\r\nDownload complete.";
                }
                catch (OperationCanceledException)
                {
                    resultsTextBox.Text += "\r\nDownload canceled.";
                }
                catch (Exception)
                {
                    resultsTextBox.Text += "\r\nDownload failed.";
                }

    // Set the CancellationTokenSource to null when the download is complete.
                cts = null;
            }

    // You can still include a Cancel button if you want to.
            private void cancelButton_Click(object sender, RoutedEventArgs e)
            {
                if (cts != null)
                {
                    cts.Cancel();
                }
            }

    // Provide a parameter for the CancellationToken.
            async Task AccessTheWebAsync(CancellationToken ct)
            {
                HttpClient client = new HttpClient();

    // Call SetUpURLList to make a list of web addresses.
                List<string> urlList = SetUpURLList();

    // ***Comment out or delete the loop.
                //foreach (var url in urlList)
                //{
                //    // GetAsync returns a Task<HttpResponseMessage>.
                //    // Argument ct carries the message if the Cancel button is chosen.
                //    // ***Note that the Cancel button can cancel all remaining downloads.
                //    HttpResponseMessage response = await client.GetAsync(url, ct);

    //    // Retrieve the website contents from the HttpResponseMessage.
                //    byte[] urlContents = await response.Content.ReadAsByteArrayAsync();

    //    resultsTextBox.Text +=
                //        String.Format("\r\nLength of the downloaded string: {0}.\r\n", urlContents.Length);
                //}

    // ***Create a query that, when executed, returns a collection of tasks.
                IEnumerable<Task<int>> downloadTasksQuery =
                    from url in urlList select ProcessURLAsync(url, client, ct);

    // ***Use ToArray to execute the query and start the download tasks.
                Task<int>[] downloadTasks = downloadTasksQuery.ToArray();

    // ***Call WhenAny and then await the result. The task that finishes
                // first is assigned to firstFinishedTask.
                Task<int> firstFinishedTask = await Task.WhenAny(downloadTasks);

    // ***Cancel the rest of the downloads. You just want the first one.
                cts.Cancel();

    // ***Await the first completed task and display the results.
                // Run the program several times to demonstrate that different
                // websites can finish first.
                var length = await firstFinishedTask;
                resultsTextBox.Text += String.Format("\r\nLength of the downloaded website:  {0}\r\n", length);
            }

    // ***Bundle the processing steps for a website into one async method.
            async Task<int> ProcessURLAsync(string url, HttpClient client, CancellationToken ct)
            {
                // GetAsync returns a Task<HttpResponseMessage>.
                HttpResponseMessage response = await client.GetAsync(url, ct);

    // Retrieve the website contents from the HttpResponseMessage.
                byte[] urlContents = await response.Content.ReadAsByteArrayAsync();

    return urlContents.Length;
            }

    // Add a method that creates a list of web addresses.
            private List<string> SetUpURLList()
            {
                List<string> urls = new List<string>
                {
                    "http://msdn.microsoft.com",
                    "http://msdn.microsoft.com/en-us/library/hh290138.aspx",
                    "http://msdn.microsoft.com/en-us/library/hh290140.aspx",
                    "http://msdn.microsoft.com/en-us/library/dd470362.aspx",
                    "http://msdn.microsoft.com/en-us/library/aa578028.aspx",
                    "http://msdn.microsoft.com/en-us/library/ms404677.aspx",
                    "http://msdn.microsoft.com/en-us/library/ff730837.aspx"
                };
                return urls;
            }
        }
        // Sample output:

    // Length of the downloaded website:  158856

    // Download complete.
    }

在完成一个异步任务后取消剩余任务(C#)的更多相关文章

  1. 如何设计一个异步Web服务——任务调度

    接上一篇<如何设计一个异步Web服务——接口部分> Application已经将任务信息发到了Service服务器中,接下来,Service服务器改如何对自身的资源进行合理分配以满足App ...

  2. 分享一个异步任务在遇到IO异常时支持递归回调的辅助方法

    public void TryAsyncActionRecursively<TAsyncResult>( string asyncActionName, Func<Task<T ...

  3. 深入理解Tornado——一个异步web服务器

    本人的第一次翻译,转载请注明出处:http://www.cnblogs.com/yiwenshengmei/archive/2011/06/08/understanding_tornado.html原 ...

  4. 一个异步任务接收两个url下载两个图片

    有两个url,一个是下载用户头像的url,一个是下载用户上传图片的url,想要用一个异步任务同时下载这两个图片. 程序的下载任务是这么执行的,先接受url参数,然后调用 imgUrls = infoP ...

  5. Netty实现的一个异步Socket代码

    本人写的一个使用Netty实现的一个异步Socket代码 package test.core.nio; import com.google.common.util.concurrent.ThreadF ...

  6. 并发编程 —— 自己写一个异步回调 API

    1. 前言 在并发编程中,异步回调的效率不言而喻,在业务开发中,如果由阻塞的任务需要执行,必然要使用异步线程.并且,如果我们想在异步执行之后,根据他的结果执行一些动作. JDK 8 之前的 Futur ...

  7. 如何设计一个异步Web服务——接口部分

    需求比较简单,提供一个异步Web服务供使用者调用.比如说,某应用程序需要批量地给图片加lomo效果.由于加lomo效果这个操作非常消耗CPU资源,所以我们需要把这个加lomo效果的程序逻辑放到一台单独 ...

  8. AJAX其实就是一个异步网络请求

    AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML).其实就是一个异步网络请求. 一.创建对象 var xmlhttp; if (w ...

  9. WPF 多线程 UI:设计一个异步加载 UI 的容器

    对于 WPF 程序,如果你有某一个 UI 控件非常复杂,很有可能会卡住主 UI,给用户软件很卡的感受.但如果此时能有一个加载动画,那么就不会感受到那么卡顿了.UI 的卡住不同于 IO 操作或者密集的 ...

随机推荐

  1. iOS - OC 与 Swift 互相操作

    前言 在 Swift 语言中,我们可以使用 Objective-C.C 语言编写代码,我们可以导入任意用 Objective-C 写的 Cocoa 平台框架.Objective-C 框架或 C 类库. ...

  2. iOS添加Prefix Header

    1. 添加Prefix Header 注: Xcode 6苹果默认去掉prefix Header, 用以提高原文件的复用性, 便于迁移. 并且可以一定程度上减少Build Time. 解决办法: (1 ...

  3. [转载] tcp那些事1

    原文: http://coolshell.cn/articles/11564.html TCP是一个巨复杂的协议,因为他要解决很多问题,而这些问题又带出了很多子问题和阴暗面.所以学习TCP本身是个比较 ...

  4. PostgreSQL数据库服务端监听设置及客户端连接方法教程

    众所周知,PostgreSQL 是一个自由的对象-关系数据库服务器(数据库管理系统),是一个可以免费使用的开放源代码数据库系统.本文详细介绍了PostgreSQL数据库服务端监听设置及客户端连接方法, ...

  5. Python中的join()函数split()函数

    函数:string.join() Python中有join()和os.path.join()两个函数,具体作用如下:     join():    连接字符串数组.将字符串.元组.列表中的元素以指定的 ...

  6. 【服务器防护】WEB防护 - WEBSHELL攻击探测【转载】

    原文:http://www.2cto.com/Article/201511/451757.html 1. 什么是webshell?     基于b/s架构的软件部署在Internet上,那么安全性是必 ...

  7. Mybatis调用Mysql存储过程

    在我的后台系统中,今天需要使用到存储过程.存储过程还真没写过,今天就写了个存储过程.使用在后台中. 其实这个接口功能  是涉及几张表的修改,删除,新增的.就写个一个存储过程. 存储过程: ), ),) ...

  8. hiho_1089_floyd最短路

    题目 floyd算法求所有顶点之间的最短路,典型的模板题.唯一需要注意的是两个顶点之间可能有多条边直接相连,在初始化的时候,直接选择最小的长度作为两点间的距离即可. 实现 #include<io ...

  9. 【ros】Create a ROS package:package dependencies报错

    $rospack depends1 beginner_tutorials 报错:Erros:could notn call python function 'rosdep2.rospack.init_ ...

  10. mysql 截断

    当id为int是,如果是10位数,可以插入,primary key不能重复插入,其默认值可以为NULL一个varchar字段的值如果长度设定为255,则如果其长度为256也可以插入,但已经被截取到了2 ...