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.