0

我需要解析类似于 XML 的大文本。因为它不在内存中的文本(我有一个 StreamReader 对象)将该流放在内存中是我花费最多时间的地方。所以在一个线程上,我将该流放入一个数组(内存)中。我有另一个线程来处理那个数组。但我有奇怪的行为。例如看看这张图片:

在此处输入图像描述

请注意,listToProcess[counter] = buffer 现在应该listToProcess[10] = buffer注意调试器说listToProcess[10]=null为什么!?. 另一个线程只是读取它不修改它们的项目。起初我认为也许另一个线程正在使 item = null 但事实并非如此。为什么我会遇到这种行为?


如果你想在这里看到我的代码,它是:

        Semaphore sem = new Semaphore(0, 1000000);
        bool w;
        bool done = false;

        // this task is responsible for parsing text created by main thread. Main thread
        // reads text from the stream and places chunks in listToProces[]
        var task1 = Task.Factory.StartNew(() =>
        {
            sem.WaitOne(); // wait so there are items on list (listToProcess) to work with                
                                // counter to identify which chunk of char[] in listToProcess we are ading to the dictionary
                int indexOnList = 0;

                while (true)
                {
                    if (listToProcess[indexOnList] == null)
                    {
                        if (done)
                            break;

                        w = true;
                        sem.WaitOne();
                        w = false;



                        if (done)
                            break;

                        if (listToProcess[indexOnList] == null)
                        {
                            throw new NotFiniteNumberException();
                        }
                    }

                    // add chunk to dictionary
                    ProcessChunk(listToProcess[indexOnList]);

                    indexOnList++;
                }

        }); // close task1

        bool releaseSem = false;

        // this main thread is responsible for placing the streamreader into chunks of char[] so that
        // task1 can start processing those chunks
        int counter = 0;
        while (true)
        {
            char[] buffer = new char[2048];

            // unparsedDebugInfo is a streamReader object
            var charsRead = unparsedDebugInfo.Read(buffer, 0, buffer.Length);

            if (charsRead < 1)
            {
                listToProcess[counter] = pattern;
                break;
            }

            listToProcess[counter] = buffer;
            counter++;

            if (releaseSem)
            {
                sem.Release();
                releaseSem = false;
            }

            if (counter == 10 || w)
            {
                releaseSem = true;
            }
        }

        done = true;

        sem.Release();
       task1.Wait();

编辑

换句话说,对不起,我为什么要达到这个断点:

在此处输入图像描述

我认为计数器是问题所在,但也许我的信号量做错了......

4

1 回答 1

7

你有一个counter++所以你之前更新的那个是索引 9,而不是索引 10。

含义:您声称它设置

listToProcess[10] = buffer:

不正确:它设置

listToProcess[9] = buffer:
于 2012-07-11T16:04:22.537 回答