参考

利用Task,Async/Await实现异步执行

 public class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 500; i++)
            {
                Task<int> s = myFuncAsync2(i, i + 1);
            }
            TEST3();
            Console.ReadKey();
        }
        static public async Task<int> myFuncAsync2(int a, int b)
        {
            Console.WriteLine($"请求值:{a}-----{b}");
            //int sum = await Task.Run(() => { Thread.Sleep(20000); return a + b; });
            //return sum;
            return await Task.Run(() =>
            {
                Thread.Sleep(200000);
                var s = TEST(a, b);
                return s;
            });
        }
        public static int TEST(int a, int b)
        {
            return a + b;
        }
        public static void TEST3()
        {
            Console.WriteLine($"不管前面的堵塞");
        }
    }

这样写无异步效果==>Task<T>.Result造成死锁

 

 这样就可以

 

 

 

 

利用委托回调实现异步

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace ConsoleApp7
{
    class Program
    {
        public delegate void AddHandler(int i);
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
               // Thread.Sleep(2000);
                HandlerUploadData(i);
            }
            Console.ReadKey();
        }
       static private void HandlerUploadData(int i)
        {
            AddHandler handler = new AddHandler(PrintingTime);
            handler.BeginInvoke(i, null, null);//异步调用可传多参
            //handler.Invoke(i);//同步调用
        }

       static  private void PrintingTime(int i)
        {
            Thread.Sleep(2000);
            Console.WriteLine($"执行时间{DateTime.Now},执行人:{i}");
        }
    }
}
posted on 2019-12-16 15:41  红磨坊后的白桦树  阅读(308)  评论(0编辑  收藏  举报