通过多线程将项添加到ConcurrentBag

问题描述 投票:-2回答:1

我正在尝试向ConcurrentBag添加多个值,但实际上没有值进入。起初我尝试使用List,但显然不是“线程安全”,所以我四处搜索,似乎人们建议使用ConcurrentBag。我尝试使用带有List的Thread.Sleep(100)并且工作正常,但速度较慢。如何正确添加值? debuger总是显示“Count:0”。这是我的代码:

 foreach (KeyValuePair<string, string> entry in test_Words)
            {
                Form1.fr.progressBar1.Value++;
                new Thread(delegate () {
                    switch (test_Type)
                    {
                        case "Definitions":
                            bagOfExercises.Add(Read(Definitions.get(entry.Value, entry.Key)));
                            break;
                        case "Examples":
                            bagOfExercises.Add(Read(Examples.get(entry.Value, entry.Key)).Replace(entry.Key, new string('_', entry.Key.Length)));
                            break;
                    }
                }).Start();           
            }
c# multithreading list
1个回答
1
投票

PLinq示例:

Func<KeyValuePair<string, string>, string> get;

if(test_Type == "Definitions") 
{
    get = kvp => Read(Definitions.get(kvp.Value, kvp.Key));
}
else
{
    get = kvp => Read(Examples.get(kvp.Value, kvp.Key)).Replace(entry.Key, new string('_', kvp.Key.Length)));
}

var results = test_Words.AsParallel()
                        .WithDegreeOfParallelism(test_Words.Count())
                        .Select(get)
                        .ToList();

这会尝试每个条目使用一个线程。通常情况下,PLinq将决定什么是资源的最佳使用,但在这种情况下,我们知道PLinq无法知道的事情:我们在外部资源上等待很多,这可以大规模并行完成。

© www.soinside.com 2019 - 2024. All rights reserved.