Skip to content

Instantly share code, notes, and snippets.

@Nilzor
Created August 22, 2012 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nilzor/3424332 to your computer and use it in GitHub Desktop.
Save Nilzor/3424332 to your computer and use it in GitHub Desktop.
ExclusiveTaskQueue with tests
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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment