WorkShift
The dispatcher needs to do different things at different,
non-overlapped times. For example, non-parallel tests may
not be run at the same time as parallel tests. We model
this using the metaphor of a working shift. The WorkShift
class associates one or more WorkItemQueues with one or
more TestWorkers.
Work in the queues is processed until all queues are empty
and all workers are idle. Both tests are needed because a
worker that is busy may end up adding more work to one of
the queues. At that point, the shift is over and another
shift may begin. This cycle continues until all the tests
have been run.
using System;
using System.Collections.Generic;
using System.Threading;
namespace NUnit.Framework.Internal.Execution
{
public class WorkShift
{
private static Logger log = InternalTrace.GetLogger("WorkShift");
private object _syncRoot = new object();
private int _busyCount;
private string _name;
public bool IsActive { get; set; }
public IList<WorkItemQueue> Queues { get; set; }
public IList<TestWorker> Workers { get; set; }
public bool HasWork {
get {
foreach (WorkItemQueue queue in Queues) {
if (!queue.IsEmpty)
return true;
}
return false;
}
}
public event EventHandler EndOfShift;
public WorkShift(string name)
{
_name = name;
IsActive = false;
Queues = new List<WorkItemQueue>();
Workers = new List<TestWorker>();
}
public void AddQueue(WorkItemQueue queue)
{
log.Debug("{0} shift adding queue {1}", _name, queue.Name);
Queues.Add(queue);
if (IsActive)
queue.Start();
}
public void Assign(TestWorker worker)
{
log.Debug("{0} shift assigned worker {1}", _name, worker.Name);
Workers.Add(worker);
worker.Busy += delegate {
Interlocked.Increment(ref _busyCount);
};
worker.Idle += delegate {
if (Interlocked.Decrement(ref _busyCount) == 0) {
lock (_syncRoot) {
if (_busyCount == 0 && !HasWork)
EndShift();
}
}
};
worker.Start();
}
public void Start()
{
log.Info("{0} shift starting", _name);
IsActive = true;
foreach (WorkItemQueue queue in Queues) {
queue.Start();
}
}
public void EndShift()
{
log.Info("{0} shift ending", _name);
IsActive = false;
foreach (WorkItemQueue queue in Queues) {
queue.Pause();
}
if (this.EndOfShift != null)
this.EndOfShift(this, EventArgs.Empty);
}
public void ShutDown()
{
IsActive = false;
foreach (WorkItemQueue queue in Queues) {
queue.Stop();
}
}
public void Cancel(bool force)
{
if (force)
IsActive = false;
foreach (TestWorker worker in Workers) {
worker.Cancel(force);
}
}
}
}