APM 模式1

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Joyhen/article/details/80916597
class Calculator
    {
        public IAsyncResult BeginCalculate(AsyncCallback ac, object state)
        {
            Console.WriteLine("Calling BeginCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId);
            Task<string> f = Task<string>.Factory.StartNew(x => Compute(), state);
            if (ac != null)
            {
                f.ContinueWith(x => ac(f));
            }
            return f;
        }

        public string Compute()
        {
            Console.WriteLine("Calling compute on thread {0}", Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(5000);
            return "3.14159265358979323846264338327950288";
        }

        public string EndCalculate(IAsyncResult ar)
        {
            Console.WriteLine("Calling EndCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId);
            return ((Task<string>)ar).Result;
        }
    }
static void Main(string[] args)
        {
            Calculator calc = new Calculator();

            AsyncCallback callBack = new AsyncCallback(PrintResult);
            IAsyncResult ar = calc.BeginCalculate(callBack, calc);


            Console.WriteLine("Working...");
            Thread.Sleep(2000);
            Console.ReadLine();
        }

        public static void PrintResult(IAsyncResult result)
        {
            Calculator c = result.AsyncState as Calculator;
            if (c == null) return;

            string piString = c.EndCalculate(result);

            Console.WriteLine("Calling PrintResult on thread {0}; result = {1}",
                        Thread.CurrentThread.ManagedThreadId, piString);
        }

AsyncCallback callBack = new AsyncCallback(PrintResult);

是一个实例化的异步委托回调函数,其实可以直接用

IAsyncResult ar = calc.BeginCalculate(iar => PrintResult(iar), calc);

的方式执行 。参考:https://docs.microsoft.com/zh-cn/dotnet/standard/parallel-programming/tpl-and-traditional-async-programming

如何:使用 Async 和 Await 并行发起多个 Web 请求 (C#):

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/how-to-make-multiple-web-requests-in-parallel-by-using-async-and-await

展开阅读全文

没有更多推荐了,返回首页