线程中的奇怪行为

时间:2019-11-08 14:21:22

标签: c# multithreading linq .net-core thread-safety

我正在使用Linq在循环中创建新线程并启动它们,然后在以下循环中加入线程。但是,第一个循环在加入线程之前引发了一个我非常困惑的异常。即使indexOfHeaders仅包含3个元素(索引为0,1,2),我仍得到索引超出范围的异常且i = 3。但是,甚至更奇怪的是,即使所有其他局部变量都是可见的,我在调试器中遇到异常时也看不到int numberOfThreads值。这是因为我使用linq或三元运算符不正确吗?当我在调试器中缓慢浏览代码时,这些都无法重现。

private static void DecodeFileData(byte[] dataBuffer, UInt64 header, UInt64 trailer)
{
    byte[] headerBytesReceive = BitConverter.GetBytes(header);
    byte[] trailerBytesReceive = BitConverter.GetBytes(trailer);
    IEnumerable<int> indexOfHeaders = StartingIndex(dataBuffer, headerBytesReceive); //int indexOfHeader = Array.IndexOf(HundredKBBuffer, headerBytesReceive);
    // spawn up to 10 threads that look at the byte array for the right data
    SerialTest.DataFileWriter fileWriter = new SerialTest.DataFileWriter();
    int numberOfThreads = indexOfHeaders.Count() < 10 ? indexOfHeaders.Count() : 10;
    List<Thread> threadList = new List<Thread>();
    for (int i = 0; i < numberOfThreads; i++)
    {
        Thread decodeThread = new Thread(() => DecodeDataAsync(dataBuffer, headerBytesReceive, trailerBytesReceive, indexOfHeaders.ElementAt(i), fileWriter));
        threadList.Add(decodeThread);
        decodeThread.Start();
    }
    for (int i = 0; i < threadList.Count; i++)
        threadList.ElementAt(i).Join();
}

public static void DecodeDataAsync(byte[] dataBuffer, byte[] headerBytesReceive, byte[] trailerBytesReceive, int indexOfHeader, SerialTest.DataFileWriter fileWriter)
{ //lots of file writing and stuff that is irrelevent

DecodeFileData是从另一种方法同步调用的。 从我发布的代码中可以看到,DecodeDataAsync是异步的。

1 个答案:

答案 0 :(得分:2)

您需要注意的两件事:

首先,您正在传递共享状态:

byte[] dataBuffer, byte[] headerBytesReceive, byte[] trailerBytesReceive, int indexOfHeader, SerialTest.DataFileWriter fileWriter

第二,变量i在线程本地 NOT

DecodeDataAsync(dataBuffer, headerBytesReceive, trailerBytesReceive, indexOfHeaders.ElementAt(i), fileWriter));

创建一个包装函数,将其复制到局部变量中并传递到线程中。