コードを読みやすくするために、以下のコードを変更するにはどうすればよいですか?
a)「workThreadMethod()」を独自のクラスに移動します
b)このワーカースレッドクラスにメインの「プログラム」クラスからの静的変数を参照するコードがない
c)上記は主な2つの要件ですが、副作用として、テスト容易性のためにワーカースレッドクラスメソッドのテストが容易になり、理想的にはIOC(Ninjectなど)を介したテストに役立つことを期待しています。コンセプト[これが意味をなさない場合は、質問の目的のためにこの点を無視してください]
解決についてよくわからない主な課題は、元のスレッドと新しいスレッドの間の2つの異なる共有変数(1つは新しいスレッドが追加するConcurrentQueue、もう1つは元のスレッドが追加するbool変数)をどのように処理するかです。スレッドは、いつ停止するかを新しいスレッドに示すために使用します)
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
namespace TestConsoleApp
{
class Program
{
// Main Thread uses to indicate to New Thread to stop
private static bool _shouldStop = false;
// New Thread uses to pass back result to Main Thread
private static long _results = 0;
// Main Thread passes ongoing updates to New Thread via this queue
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); // Add test data to queue
Debug.WriteLine("Queue : " + i);
Thread.Sleep(10);
}
Thread.Sleep(5000);
_shouldStop = true;
workThread.Join();
Debug.WriteLine("Finished TestThreads. Result = " + _results);
}
// Dequeuer Methods
private void workThreadMethod()
{
// Update Summary
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);
}
}
}
}
}
}