ManualResetEvent抛出NullReferenceException:对象引用未设置为对象的实例

时间:2016-09-06 13:05:57

标签: c# nullreferenceexception manualresetevent

代码抛出

  

NullReferenceException:未将对象引用设置为对象的实例

((ManualResetEvent)handles[i]).Set()行。我在调试时检查了句柄[i]有一个值。我做错了什么?

`               string[] fileEntries = Directory.GetFiles(pathFife);
                ManualResetEvent[] handles = new ManualResetEvent[fileEntries.Count()];
                int i = 0;
                foreach (string fullName in fileEntries)
                {
                    handles[i] = new ManualResetEvent(false);
                        var thread = new Thread(() =>
                            {
                                AddFile(fullName, month, year, user);
                                ((ManualResetEvent)handles[i]).Set();
                            });
                        thread.Start();
                    i++;
                }
                WaitHandle.WaitAll(handles);`     

1 个答案:

答案 0 :(得分:0)

i {{}}} {}} {}} {}

i中使用之前,((ManualResetEvent)handles[i]).Set();的值正在增加,此时您还没有设置{{1}的值}。

这是因为在新线程执行handles[i]之前,调用线程立即转到下一行代码i++;。这是一个典型的竞争条件。

要解决此问题,请在启动线程之前添加以下行:

((ManualResetEvent)handles[i]).Set();

然后在int j = i;中使用j代替i

((ManualResetEvent)handles[i]).Set();

当然,当您在调试器下运行代码时,线程已完全改变,因此您没有看到问题。