0

I was originally using a List for this but I changed to a ConcurrentBag after seeing that Lists where not "thread-safe".

The following is my code so far. When it runs, it will not add to the ConcurrentBag, I get a NullReferenceException - "Object reference not set to an instance of an object." and I am not sure what the problem is as I do not have much experience with threads.

static ConcurrentBag<String> urls;

// ...

static void buildThreads()
{
    for (int i = 0; i < threads; i++)
    {
        Thread thread = new Thread(buildTokens);
        thread.Start();
    }
}

static void buildTokens()
{
    while (true)
    {
        if (numSockets < tokens)
        {
            getUrl();

            numSockets++;
            Console.WriteLine(numSockets + "/" + tokens);
        }
    }
}

static void getUrl()
{
    urls.Add("test");
}

I would appreciate any help. Thanks.

Dan
  • 3,879
  • 5
  • 36
  • 50
  • 1
    Try `static ConcurrentBag urls = new ConcurrentBag();` – Mike Zboray Mar 08 '14 at 18:33
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – nvoigt Mar 08 '14 at 18:36

3 Answers3

2

Perform this instantiating before accessing this object, it's contains a null reference right now:

static ConcurrentBag<string> urls = new ConcurrentBag<string>();
Yair Nevet
  • 12,725
  • 14
  • 66
  • 108
2

You have to "new" your concurrent bag (create an instance):

static ConcurrentBag<String> urls = new ConcurrentBag<String>()

If you are using Visual Studio to build and debug your code you should be able to place a break point on the line where you add to the bag and notice the value of the variable is "null"

juanvilla
  • 196
  • 4
1

Problem : Your ConcurrentBag variable urls is null as you have not initialised it properly.

Solution: You need to initialise your ConcurrentBag variable urls properly using new keyword.

Replace This:

static ConcurrentBag<String> urls;

With This:

static ConcurrentBag<String> urls = new ConcurrentBag<String>();
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67