我有一个全球宣布的名单。使用 foreach 循环我获取数据并创建线程以处理特定记录。这里每个线程只需要处理一个数据。但是当我使用这些线程时,这些线程有时会处理多个数据。有时两次使用相同的数据。有什么方法可以同步线程吗?我的需要是:每个线程都将打开并使用该特定值,并在工作完成后关闭。请提出合适的解决方案。请在下面查看我的代码详细信息:
全局声明列表:
public static List<string[]> OutboxList = new List<string[]>();
从列表中获取数据并打开线程:
foreach (string[] OutBoxFields in OutboxList)
{
// default value of OutBoxFields[6] is QUE. Values are: a,b,c,d,e
Console.WriteLine("From foreach loop: Data:" + OutBoxFields[2] + "|Status:" + OutBoxFields[6] + "\n");
Thread OutboxThread = new Thread(() => OutboxThreadProcessor(OutBoxFields));
OutboxThread.Start();
}
线程方法:
static void OutboxThreadProcessor(string[] OutBoxFields)
{
string var = "a";
if (OutBoxFields[2] == var)
OutBoxFields[6] = "SENT";
Console.WriteLine("From Thread Method: Data:" + OutBoxFields[2] + "|Status:" + OutBoxFields[6] + "\n");
}
完成工作后检查阵列:
foreach (string[] NewOutBoxFields in OutboxList)
{
Console.WriteLine("From new foreach:" + NewOutBoxFields[2] + "|" + NewOutBoxFields[6] + "\n");
}
电流输出:
From foreach loop: Data:c|Status:QUE
From foreach loop: Data:d|Status:QUE
From foreach loop: Data:a|Status:QUE
From foreach loop: Data:e|Status:QUE
From Thread Method: Data:e|Status:QUE
From Thread Method: Data:e|Status:QUE
From foreach loop: Data:b|Status:QUE
From Thread Method: Data:e|Status:QUE
From Thread Method: Data:b|Status:QUE
From Thread Method: Data:b|Status:QUE
From new foreach:c|QUE
From new foreach:d|QUE
From new foreach:a|QUE
From new foreach:e|QUE
From new foreach:b|QUE
预期输出:
From foreach loop: Data:c|Status:QUE
From Thread Method: Data:c|Status:QUE
From foreach loop: Data:d|Status:QUE
From Thread Method: Data:d|Status:QUE
From foreach loop: Data:a|Status:QUE
From Thread Method: Data:a|Status:SENT
From foreach loop: Data:e|Status:QUE
From Thread Method: Data:e|Status:QUE
From foreach loop: Data:b|Status:QUE
From Thread Method: Data:b|Status:QUE
From new foreach:c|QUE
From new foreach:d|QUE
From new foreach:a|SENT
From new foreach:e|QUE
From new foreach:b|QUE