簡體   English   中英

通過多線程向 ConcurrentBag 添加項目

[英]Add items to ConcurrentBag by multithreading

我正在嘗試向 ConcurrentBag 添加多個值,但實際上沒有值進入。 起初我嘗試使用 List,但這顯然不是“線程安全”,所以我四處搜索,似乎人們建議使用 ConcurrentBag。 我嘗試將 Thread.Sleep(100) 與 List 一起使用,效果很好,但速度較慢。 如何正確添加值? 調試器總是顯示“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();           
            }

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 無法知道的事情:我們在外部資源上等待很多,這可以大規模並行完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM