[原]C#多线程异步操作

AsyncEnumerator版

            BlockingCollection<string> idsToProcess = new BlockingCollection<string>();
            idsToProcess.Add("a");
            idsToProcess.Add("b");
            idsToProcess.Add("c");
            Timer t = null;
            t = new Timer(async _ =>
            {
                idsToProcess.CompleteAdding();
                await t.DisposeAsync();
            }, null, 5000, Timeout.Infinite);
            idsToProcess.GetConsumingEnumerable().ParallelForEachAsync(async id =>
            {
                await Task.Run(() =>
                {
                    Console.WriteLine(id);
                });
            }).GetAwaiter().GetResult();

Nito.AsyncEx版

            BlockingCollection<string> idsToProcess = new BlockingCollection<string>();
            idsToProcess.Add("a");
            idsToProcess.Add("b");
            idsToProcess.Add("c");
            Timer t = null;
            t = new Timer(async _ =>
            {
                idsToProcess.CompleteAdding();
                await t.DisposeAsync();
            }, null, 5000, Timeout.Infinite);
            Parallel.ForEach(idsToProcess.GetConsumingEnumerable(),
                id =>
                {
                    AsyncContext.Run(async () =>
                    {
                        await Task.Run(() =>
                        {
                            Console.WriteLine(id);
                        }); 
                    });
                });

 

            var services = new ServiceCollection();
           services.AddHttpClient("GitHub", httpClient =>
           {
               httpClient.BaseAddress = new Uri("http://192.168.5.238:4000/");
               httpClient.DefaultRequestHeaders.Add(
                   "Accept", "*/*");
               httpClient.DefaultRequestHeaders.Add(
                   "User-Agent", "'Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20121202 Firefox/20.0'");
               httpClient.DefaultRequestHeaders.Connection.Add("Keep-Alive");
           }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
           {
               MaxConnectionsPerServer = 1000
           })
               ;
           var serviceProvider = services.BuildServiceProvider();
           var httpFactory = serviceProvider.GetService<IHttpClientFactory>();
           ConcurrentBag<string> bags = new ConcurrentBag<string>();
           if (httpFactory != null)
           {
               BlockingCollection<decimal> dts = new BlockingCollection<decimal>();
               for (int i = 0; i < 10000; i++)
               {
                   dts.Add(i);
               }
               dts.CompleteAdding();
               int idx = 0;
               Parallel.ForEach(dts,new ParallelOptions(){MaxDegreeOfParallelism = 2}, item =>
               {
                   var httpClient = httpFactory.CreateClient("GitHub");
                   var result = httpClient.GetAsync($"temp").Result;
                   Interlocked.Increment(ref idx);
               });

           }
//-------------------------------------------------------
           var cancellationTokenSource = new CancellationTokenSource();
           var cancellationToken=cancellationTokenSource.Token;
           var tasks=new List<Task>();
           SemaphoreSlim semaphore = new SemaphoreSlim(20);
           for (int i = 0; i < 10000; i++)
           {
               await semaphore.WaitAsync(cancellationToken);
               tasks.Add(Task.Run(async () =>
               {
                   try
                   {
                       var httpClient = httpFactory?.CreateClient("GitHub");
                       var result = await httpClient?.GetAsync($"temp", cancellationToken)!;
                   }
                   finally
                   {
                       semaphore.Release();
                   }
                 
               },cancellationToken));
           }
           await Task.WhenAll(tasks);            

 

posted @ 2020-03-02 23:10  月渊  阅读(300)  评论(0)    收藏  举报