创建线程时出现NullReferenceException

我正在看这个线程创建一个简单的线程池。 在那里,我遇到了@ MilanGardian对.NET 3.5的回应,它很优雅并且符合我的目的:

using System; using System.Collections.Generic; using System.Threading; namespace SimpleThreadPool { public sealed class Pool : IDisposable { public Pool(int size) { this._workers = new LinkedList(); for (var i = 0; i  0) { Monitor.Wait(this._tasks); } this._disposed = true; Monitor.PulseAll(this._tasks); // wake all workers (none of them will be active at this point; disposed flag will cause then to finish so that we can join them) waitForThreads = true; } } if (waitForThreads) { foreach (var worker in this._workers) { worker.Join(); } } } public void QueueTask(Action task) { lock (this._tasks) { if (this._disallowAdd) { throw new InvalidOperationException("This Pool instance is in the process of being disposed, can't add anymore"); } if (this._disposed) { throw new ObjectDisposedException("This Pool instance has already been disposed"); } this._tasks.AddLast(task); Monitor.PulseAll(this._tasks); // pulse because tasks count changed } } private void Worker() { Action task = null; while (true) // loop until threadpool is disposed { lock (this._tasks) // finding a task needs to be atomic { while (true) // wait for our turn in _workers queue and an available task { if (this._disposed) { return; } if (null != this._workers.First && object.ReferenceEquals(Thread.CurrentThread, this._workers.First.Value) && this._tasks.Count > 0) // we can only claim a task if its our turn (this worker thread is the first entry in _worker queue) and there is a task available { task = this._tasks.First.Value; this._tasks.RemoveFirst(); this._workers.RemoveFirst(); Monitor.PulseAll(this._tasks); // pulse because current (First) worker changed (so that next available sleeping worker will pick up its task) break; // we found a task to process, break out from the above 'while (true)' loop } Monitor.Wait(this._tasks); // go to sleep, either not our turn or no task to process } } task(); // process the found task this._workers.AddLast(Thread.CurrentThread); task = null; } } private readonly LinkedList _workers; // queue of worker threads ready to process actions private readonly LinkedList _tasks = new LinkedList(); // actions to be processed by worker threads private bool _disallowAdd; // set to true when disposing queue but there are still tasks pending private bool _disposed; // set to true when disposing queue and no more tasks are pending } public static class Program { static void Main() { using (var pool = new Pool(5)) { var random = new Random(); Action randomizer = (index => { Console.WriteLine("{0}: Working on index {1}", Thread.CurrentThread.Name, index); Thread.Sleep(random.Next(20, 400)); Console.WriteLine("{0}: Ending {1}", Thread.CurrentThread.Name, index); }); for (var i = 0; i  randomizer(i1)); } } } } } 

我使用如下:

 static void Main(string[] args) { ... ... while(keepRunning) { ... pool.QueueTask(() => DoTask(eventObject); } ... } private static void DoTask(EventObject e) { // Do some computations pool.QueueTask(() => DoAnotherTask(eventObject)); // this is a relatively smaller computation } 

运行代码大约两天后,我收到以下exception:

 Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at System.Collections.Generic.LinkedList`1.InternalInsertNodeBefore(LinkedListNode`1 node, LinkedListNode`1 newNode) at System.Collections.Generic.LinkedList`1.AddLast(T value) at MyProg.Pool.Worker() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() 

我无法弄清楚导致这种情况的原因,因为我无法再次收到此错误。 对于如何解决这个问题,有任何的建议吗?

似乎访问_workers链接列表未正确同步。 考虑这种情况:

让我们假设在某些时候this._workets列表包含一个项目。

第一个线程调用this._workers.AddLast(Thread.CurrentThread); 但是在一个非常特殊的地方被打断 – 在AddLast()方法中:

 public void AddLast(LinkedListNode node) { this.ValidateNewNode(node); if (this.head == null) { this.InternalInsertNodeToEmptyList(node); } else { // here we got interrupted - the list was not empty, // but it would be pretty soon, and this.head becomes null // InternalInsertNodeBefore() does not expect that this.InternalInsertNodeBefore(this.head, node); } node.list = (LinkedList) this; } 

其他线程调用this._workers.RemoveFirst(); 。 该语句周围没有lock() ,所以它完成,现在列表为空。 AddLast()现在应该调用InternalInsertNodeToEmptyList(node); 但它不能因为条件已被评估。

在单个this._workers.AddLast()行周围放置一个简单的lock(this._tasks)可以防止出现这种情况。

其他不良情况包括两个线程同时将项添加到同一列表。

我想我发现了这个问题。 代码示例有一个错过的lock()

 private void Worker() { Action task = null; while (true) // loop until threadpool is disposed { lock (this._tasks) // finding a task needs to be atomic { while (true) // wait for our turn in _workers queue and an available task { .... } } task(); // process the found task this._workers.AddLast(Thread.CurrentThread); task = null; } } 

锁应该扩展或包裹在this._workers.AddLast(Thread.CurrentThread);

如果您查看修改LinkedList (Pool.QueueTask)的其他代码,它将被包装在一个lock