这是我的代码:
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
第二个没有打印出来,我怎么能纠正这个?
答案 0 :(得分:1)
问题是Dictionary不是线程安全的。您想使用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();
}
}
答案 1 :(得分:0)
理想情况下,您应该使用ConcurrentDictionary。