In this implementation Task.Factory.StartNew
will never return thread to thread pool because it contains while(true) with Thread.Sleep. Is it right? How to check queue
that it has task that need to be done?
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Helper h = new Helper();
PlayWithQueue s = new PlayWithQueue();
s.AddToQueueForExecution(() => { h.Indicate(1); });
s.AddToQueueForExecution(() => { h.Indicate(2); });
s.AddToQueueForExecution(() => { h.Indicate(3); });
s.AddToQueueForExecution(() => { h.Indicate(4); });
s.AddToQueueForExecution(() => { h.Indicate(5); });
s.AddToQueueForExecution(() => { h.Indicate(6); });
Console.ReadKey();
}
}
public class PlayWithQueue
{
private readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();
public PlayWithQueue()
{
var task = Task.Factory.StartNew(ThreadProc);
}
public void AddToQueueForExecution(Action action)
{
queue.Enqueue(action);
}
private void ThreadProc()
{
while (true)
{
Action item;
bool isSuccessfull = false;
isSuccessfull = queue.TryDequeue(out item);
if (isSuccessfull)
{
item();
}
System.Threading.Thread.Sleep(100);
}
}
}
public class Helper
{
public void Indicate(int number)
{
Random rnd = new Random();
int timeDelay = rnd.Next(1000, 5000);
Console.WriteLine("Start" + number.ToString());
System.Threading.Thread.Sleep(timeDelay);
Console.WriteLine("End" + number.ToString() + " " + timeDelay.ToString());
}
}
}