First, I want to say that this code works, but I want to make sure this is the right way of doing it. I am writing this for a SMS text API that loops through each phone number. I sometimes gets hung up on 1 number or just takes time. It roughly takes 6-8 sec per number. So I thought I would write something that would make it multitreaded. I wrote this to allow the number of threads at one time to go up depending on the work load. So, I guess this is more of a code review. Thanks.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TestTreading
{
class Program
{
static public BlockingCollection<int> Queue = new BlockingCollection<int>();
static public BlockingCollection<int> Finished = new BlockingCollection<int>();
static public BlockingCollection<Thread> Threads = new BlockingCollection<Thread>();
static public int QUCount = 0;
static public int THCount = 0;
static public int FNCount = 0;
static void Main(string[] args)
{
BuildList();
DateTime StartTime = DateTime.Now;
QUCount = Queue.Count;
THCount = Threads.Count;
FNCount = Finished.Count;
while (QUCount > 0)
{
THCount = Threads.Count;
if (THCount < 20)
{
Thread th1 = new Thread(LoopMethod);
Threads.Add(th1);
THCount = Threads.Count;
th1.Start();
}
}
DateTime EndTime = DateTime.Now;
Console.WriteLine(StartTime);
Console.WriteLine(EndTime);
Console.WriteLine(EndTime - StartTime);
Console.ReadLine();
}
static void LoopMethod()
{
int QueueItem = Queue.Take();
QUCount = Queue.Count;
for (long i = 0; i < 100000; i++)
{
long result = i / 2;
}
string Display = string.Format("ID:{0} Left In Queue:{1} Finished:{2} Threads Running:{3}", QueueItem, QUCount, FNCount, THCount);
Console.WriteLine(Display);
Thread.Sleep(10);
Finished.Add(QueueItem);
FNCount = Finished.Count;
Thread CurTh = Thread.CurrentThread;
Threads.TryTake(out CurTh);
}
static void BuildList()
{
for (long i = 0; i < 5000; i++)
{
Random RandomNum = new Random();
int Num = RandomNum.Next(1, 2);
Queue.Add(Num);
}
}
}
}