简体   繁体   English

当袋子中只有2件物品时,处理ConcurrentBag会显示5000多个任务

[英]Processing a ConcurrentBag shows over 5000 tasks when only 2 items in bag

Found the following ConcurrentBag example on Microsoft here . 此处在Microsoft上找到以下ConcurrentBag示例。

I was debugging a unit test and kind of inspecting around and the bagConsumeTasks had over 5000 items in it. 我正在调试单元测试和某种检查方式,bagConsumeTasks中包含5000多个项目。 Is this normal? 这正常吗? The bag had only 2 itmes. 袋子里只有2个主题。

在此处输入图片说明

HashSet<string> x = new HashSet<string>();
List<Task> bagConsumeTasks = new List<Task>();
int itemsInBag = 0;
while (!result.IsEmpty)
{
    bagConsumeTasks.Add(Task.Run(() =>
    {
        string item;
        if (result.TryTake(out item))
        {
            x.Add(item);
            itemsInBag++;
        }
    }));
}
Task.WaitAll(bagConsumeTasks.ToArray());

There's a race between checking result.IsEmpty and the tasks consuming items, leading the code to start more tasks than needed. 在检查result.IsEmpty和任务消耗项之间存在着竞争,导致代码启动了比所需更多的任务。

The increment of local variable itemsInBag by many tasks in parallel is also a race, but mitigated by the call to Console.WriteLine just before it. 许多任务并行执行的局部变量itemsInBag的增量也是一个竞赛,但是可以通过在其之前调用Console.WriteLine来缓解。

While in some cases this could be a bug, I guess the over-scheduling of tasks may be deliberate here, to demonstrate the class running under high contention? 尽管在某些情况下这可能是一个错误,但我想这里可能故意安排了过多的任务,以证明该类在高竞争中运行?

Because nothing else is using the concurrent bag, the example could just create a fixed number of Tasks: 因为没有其他东西在使用并发包,所以该示例只能创建固定数量的Task:

    List<Task> bagConsumeTasks = new List<Task>();
    int itemsInBag = 0;
    for (int i = 0; i < 500; i++)
    {
        bagConsumeTasks.Add(Task.Run(() =>
        {
            int item;
            if (cb.TryTake(out item))
            {
                Console.WriteLine(item);
                Interlocked.Increment(ref itemsInBag);
            }
        }));
    }
    Task.WaitAll(bagConsumeTasks.ToArray());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM