yzpopulation

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);
                        }); 
                    });
                });

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-10
  • 2021-06-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
猜你喜欢
  • 2021-11-15
  • 2022-12-23
  • 2021-12-05
  • 2021-12-05
  • 2021-04-16
  • 2021-10-05
相关资源
相似解决方案