public
Created

ExclusiveTaskQueue with tests

  • Download Gist
ExclusiveTaskQueue.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
 
public class ExclusiveTaskQueue
{
public ConcurrentExclusiveSchedulerPair _schedulerPair;
public static TaskFactory _exclusiveTaskFactory;
 
public ExclusiveTaskQueue()
{
_schedulerPair = new ConcurrentExclusiveSchedulerPair();
_exclusiveTaskFactory = new TaskFactory(_schedulerPair.ExclusiveScheduler);
}
 
public Task RunExclusively(Action action)
{
return _exclusiveTaskFactory.StartNew(action);
}
 
public Task RunExclusively(Func<Task> action)
{
return _exclusiveTaskFactory.StartNew(action).Unwrap();
}
}
 
[TestClass]
public class ExclusiveTaskQueueTest
{
[TestMethod]
public void TwoTasks_DoesNotOverlap()
{
var queue = new ExclusiveTaskQueue();
var clock = new Clock();
clock.Init();
queue.RunExclusively(() => clock.StopAfter(250, 0));
queue.RunExclusively(() => clock.StopAfter(250, 1));
 
Task.Delay(750).Wait();
Assert.IsTrue(clock.StartTime[0] < 250, "First start time was " + clock.StartTime[0] + "ms");
Assert.IsTrue(clock.StartTime[1] > 250, "Second start time was " + clock.StartTime[1] + "ms");
Assert.IsTrue(clock.EndTime[0] > 250, "First end time was " + clock.EndTime[0] + "ms");
Assert.IsTrue(clock.EndTime[1] > 500, "Second end time was " + clock.EndTime[1] + "ms");
}
}
 
internal class Clock
{
private static long _testStart;
internal long[] EndTime = new long[2];
internal long[] StartTime = new long[2];
 
public async Task StopAfter(long ms, int ix)
{
StartTime[ix] = Environment.TickCount - _testStart;
await Task.Delay((int)ms);
EndTime[ix] = Environment.TickCount - _testStart;
}
 
public void Init()
{
_testStart = Environment.TickCount;
for (int i = 0; i < 2; i++)
{
EndTime[i] = -1;
StartTime[i] = -1;
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.