タスクベースのサーバーを構築しています。私の問題は、単体テストが正しく機能していることを証明する方法です。
以下のメソッドはアプリのコアであり、しっかりしている必要があります。一連のタスクを実行したり、開始日が将来の場合はスリープしたりするために必要です。ただし、nuni gui で実行すると永久にハングアップし、http://www.testdriven.net/アドオンを使用すると実行され、バックグラウンドで実行されるため、最初から停止することはできません。 VS IDE (つまり、実行し、IDE に従って終了しますが、バックグラウンドで実行し続け、それを停止するには testdriven を強制終了する必要があります)
public Task RunPlan(plan thePlan)
{
List<BackupTask> tasks = this.nextTasks(thePlan);
List<Task> backupTasks = new List<Task>();
TimeSpan wait;
int i = 1;
Task run = new Task(() =>
{
Logging.Debug("Starting {0}", thePlan);
});
// Create a new token source
var primaryTokenSource = new CancellationTokenSource();
// Create the cancellation token to pass into the Task
CancellationToken token = primaryTokenSource.Token;
workerTokens.GetOrAdd(run, primaryTokenSource);
backupTasks.Add(run);
foreach (var t in tasks)
{
BackupTask job = t;
Task next = backupTasks.Last().ContinueWith(x =>
{
// Check to see if we've been cancelled
if (token.IsCancellationRequested)
{
Logging.Debug("Cancelled");
return;
}
//Si es en el futuro, esperar
wait = job.SuggestedDate - DateTime.Now;
if (wait.TotalSeconds > 0)
{
Logging.Debug("Sleeping {0} secs..", wait.TotalSeconds);
//http://stackoverflow.com/questions/1141617/thread-interrupt-to-stop-long-sleep-at-app-shutdown-is-there-a-better-approach
//Thread.Sleep(TimeSpan.FromSeconds(wait.TotalSeconds));
while (!stopping)
{
lock (padlock)
{
Monitor.Wait(padlock, TimeSpan.FromSeconds(wait.TotalSeconds));
}
}
}
// Check to see if we've been cancelled
if (token.IsCancellationRequested)
{
Logging.Debug("Cancelado");
return;
}
job.doWork();
},TaskContinuationOptions.LongRunning);
backupTasks.Add(next);
}
backupTasks.First().Start();
return backupTasks.Last();
}
そしてテスト:
[Test]
public void testFullBackup()
{
taskMgr.RunPlan(plans.First()).Wait();
Assert.AreEqual(0, taskMgr.workerTokens.Count());
}