Reputation: 3899
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.
Upvotes: 0
Views: 810
Reputation: 26209
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>();
Upvotes: 1
Reputation: 196
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"
Upvotes: 2
Reputation: 13003
Perform this instantiating before accessing this object, it's contains a null
reference right now:
static ConcurrentBag<string> urls = new ConcurrentBag<string>();
Upvotes: 2