Question

I'm building a task-based server. My problem is how prove with unit test is working right:

The method below is the core of the app, and need to be solid. I need it to execute the chain of task, sleep if the date to start it is in the future and so on. However when I run it with the nuni gui it hang-up forever, and with http://www.testdriven.net/ add-on it run, and get it running in the background, so I can't stop it from the VS IDE (ie, run, then finish according to the IDE, but keep running in the background and need to kill testdriven to stop it)

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();
}

And the test:

[Test]
public void testFullBackup()
{
    taskMgr.RunPlan(plans.First()).Wait();
    Assert.AreEqual(0, taskMgr.workerTokens.Count());
}

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top