How can I modify the code below so that I can, for better readability in the code:
a) move "workThreadMethod ()" to your own class
b) has no code in this working class class of static variables from the main class "Program"
c) the above requirements are the main two requirements, but I hope that as a side effect, this would ensure that workflow class methods would be easier to test for suitability and could ideally be tested through IOC (like Ninject) [ if this does not make sense, then ignore this point for the purpose of the question]
The main problem that I'm not sure about the solution is how to handle two different common variables between the source stream and the new stream (one of them is ConcurrentQueue, to which the new stream is added, and the other is the bool variable that the source stream uses, to indicate a new thread when to stop)
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
namespace TestConsoleApp
{
class Program
{
private static bool _shouldStop = false;
private static long _results = 0;
private static ConcurrentQueue<long> _workQueue = new ConcurrentQueue<long>();
static void Main(string[] args)
{
var p = new Program();
p.TestThreads();
}
public void TestThreads()
{
_shouldStop = false;
var workThread = new Thread(workThreadMethod);
workThread.Start();
for (int i = 0; i < 100; i++)
{
_workQueue.Enqueue(i);
Debug.WriteLine("Queue : " + i);
Thread.Sleep(10);
}
Thread.Sleep(5000);
_shouldStop = true;
workThread.Join();
Debug.WriteLine("Finished TestThreads. Result = " + _results);
}
private void workThreadMethod()
{
while (!_shouldStop)
{
if (_workQueue.Count == 0)
{
Thread.Sleep(10);
}
else
{
long currentValue;
bool worked = _workQueue.TryDequeue(out currentValue);
if (worked)
{
_results += currentValue;
Debug.WriteLine("DeQueue: " + currentValue);
}
}
}
}
}
}
source
share