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

 

分类:

技术点:

相关文章: