ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – 创建线程时出现NullReferenceException

2019-05-29 12:54:32  阅读:84  来源: 互联网

标签:c nullreferenceexception multithreading debugging


我在创建一个简单的线程池时看到了这个thread.在那里,我遇到了@MilanGardian’s response for .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<Thread>();
            for (var i = 0; i < size; ++i)
            {
                var worker = new Thread(this.Worker) { Name = string.Concat("Worker ", i) };
                worker.Start();
                this._workers.AddLast(worker);
            }
        }

        public void Dispose()
        {
            var waitForThreads = false;
            lock (this._tasks)
            {
                if (!this._disposed)
                {
                    GC.SuppressFinalize(this);

                    this._disallowAdd = true; // wait for all tasks to finish processing while not allowing any more new tasks
                    while (this._tasks.Count > 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<Thread> _workers; // queue of worker threads ready to process actions
        private readonly LinkedList<Action> _tasks = new LinkedList<Action>(); // 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<int> 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 < 40; ++i)
                {
                    var i1 = i;
                    pool.QueueTask(() => 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
}

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

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<T> 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<T>) this;
}

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

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

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

标签:c,nullreferenceexception,multithreading,debugging
来源: https://codeday.me/bug/20190529/1178183.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有