[英]How to add key values pairs in parallel into a dictionary in C#
這是我的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication2
{
public class c_Thread
{
public bool ThreadOngoing;
public c_Thread()
{
ThreadOngoing = false;
}
public void CallToChildThread(string key, ref List<int> nums,
ref Dictionary<string, List<int>> container)
{
container.Add(key, nums);
}
}
class Program
{
static void Main(string[] args)
{
c_Thread cc = new c_Thread();
Dictionary<string, List<int>> container1 = new Dictionary<string, List<int>>();
List<int> aList = new List<int>();
List<int> bList = new List<int>();
string printLine;
aList.Add(2);
aList.Add(4);
aList.Add(2);
bList.Add(1);
bList.Add(3);
bList.Add(1);
Thread myNewThread1 = new Thread(() =>
cc.CallToChildThread("param1", ref aList, ref container1));
myNewThread1.Start();
Thread myNewThread2 = new Thread(() =>
cc.CallToChildThread("param2", ref bList, ref container1));
myNewThread2.Start();
while (myNewThread1.ThreadState == ThreadState.Running &&
myNewThread2.ThreadState == ThreadState.Running)
{ }
foreach (string key in container1.Keys)
{
printLine = key + ": ";
foreach(int val in container1[key])
printLine += val + " ";
Console.WriteLine(printLine);
}
Console.ReadKey();
}
}
}
我正在嘗試將項目並行添加到字典中,但是打印出以下內容:
理想情況下,我想處理具有多列的txt文件,並且想將所有內容輸入到字典中,但是這需要很多時間。
param1: 2 4 2
第二個沒有打印出來,我該如何糾正?
問題是字典不是線程安全的。 您要使用ConcurrentDictionary。
public class c_Thread
{
public bool ThreadOngoing;
public c_Thread()
{
ThreadOngoing = false;
}
public void CallToChildThread(string key, ref List<int> nums, ConcurrentDictionary<string, List<int>> container)
{
container.TryAdd(key, nums);
}
}
class Program
{
static void Main(string[] args)
{
var cc = new c_Thread();
var container1 = new ConcurrentDictionary<string, List<int>>();
var aList = new List<int>();
var bList = new List<int>();
string printLine;
aList.Add(2);
aList.Add(4);
aList.Add(2);
bList.Add(1);
bList.Add(3);
bList.Add(1);
var myNewThread1 = new Thread(() => cc.CallToChildThread("param1", ref aList, container1));
myNewThread1.Start();
var myNewThread2 = new Thread(() => cc.CallToChildThread("param2", ref bList, container1));
myNewThread2.Start();
while (myNewThread1.ThreadState == ThreadState.Running && myNewThread2.ThreadState == ThreadState.Running) { }
foreach (var key in container1.Keys)
{
printLine = key + ": ";
foreach (var val in container1[key]) printLine += val + " ";
Console.WriteLine(printLine);
}
Console.ReadKey();
}
}
理想情況下,您應該使用ConcurrentDictionary 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.