zoukankan      html  css  js  c++  java
  • .NET 异步 /Task

    老版本的写法经常是以BeginXXX, EndXXX, 或者xx.xxxAsycn(........)

    新的支持 async异步关键字配合Task可读性和易用性比老板好多了。

    新旧例子:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Threading;
    using System.Globalization;
    using System.Net.Http.Headers;
    namespace ConsoleApp2
    {
        class Program
        {
            static void Main(string[] args)
            {
                TestClass class1 = new TestClass();
                class1.TestOldAsycn();
                class1.TestNewAsycn();
                Console.ReadLine();
            }
        }
    
        public class TestClass
        {
    
            private delegate long AddDel(int i, int j);
            public void TestOldAsycn()
            {
    
                AddDel del = Add;
                IAsyncResult ar = del.BeginInvoke(2, 3, MyCallBack, del);//参数里面的del 是用于残敌给回调函数调用,参看回调函数方法里的代码: ar.AsyncState as AddDel;
                                                                         //var result  del.EndInvoke(ar);//获取结果,会阻塞线程
                Console.WriteLine("Main contine .......");
    
            }
            private long Add(int i, int j)
            {
                Console.WriteLine("begin wait 5 sec---------------");
                System.Threading.Thread.Sleep(5000);
                return i + j;
            }
            /// <summary>
            /// callback 获得结果回到函数,beginXXX..里的任务执行完成后才会调用这个
            /// </summary>
            /// <param name="ar"></param>
            private void MyCallBack(IAsyncResult ar)
            {
                var d = ar.AsyncState as AddDel;//ar.AsyncState 是bingXXX里的Object
                var result = (d.EndInvoke(ar));//执行EndXXX获得结果
                Console.WriteLine("result:" + result);
            }
    
    
            //--------------新的.net更方便的Task/Asyc/Await语法----------------------------------------
    
            public async Task TestNewAsycn()
            {
    
                var result = await AddNew(2, 3);    //  OR AddNew(2,3);
                Console.WriteLine("new asycn result:" + result);
            }
    
            private async Task<long> AddNew(int i, int j)
            {
                Console.WriteLine("begin wait 5 sec---------------");
                System.Threading.Thread.Sleep(5000);
                return await Task.FromResult(i + j);
    
            }
    
    
        }
    
    
    
    
    
    }
    

      

  • 相关阅读:
    hdu 2586 How far away ?
    zoj 3195 Design the city
    hust 1022 K-diff subsequence
    poj 2253 Frogger
    poj 1470 Closest Common Ancestors
    poj 2553 The Bottom of a Graph
    poj 1236 Network of Schools
    poj 3694 Network
    uva 10131 Is Bigger Smarter ? (简单dp 最长上升子序列变形 路径输出)
    2014年百度之星程序设计大赛
  • 原文地址:https://www.cnblogs.com/wgscd/p/13475113.html
Copyright © 2011-2022 走看看