private void startRoute1(FileRouteFactory.FileRouteType frType, List<string> files, List<BaseTypes.FileType> fts, IFileHelper io)
{
const int numTasks = 9;
// Set up the cancellation source and get the token.
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
// Set up the tasks
Task[] tasks = new Task[numTasks];
for (int i = 0; i < numTasks; i++)
tasks[i] = Task.Factory.StartNew(() => new Worker().PerformTask(token), token);
// Now the tasks are all set up, show the state.
// Most will be WaitingToRun, some will be Running
foreach (Task t in tasks.OrderBy(t => t.Id))
Console.WriteLine("Tasks {0} state: {1}", t.Id, t.Status);
// Give some of the tasks a chance to do something.
Thread.Sleep(1500);
// Cancel the tasks
//Debug.WriteLine("Cancelling tasks");
//tokenSource.Cancel();
//Debug.WriteLine("Cancellation Signalled");
try
{
int idx = 0;
do
{
if (this.CheckStop())
{
DiagnosticHelper.DebugWriteLine(this.DisplayString() + " -> " + frType.ToString() + " , calling CancellationTokenSource.Cancel...");
tokenSource.Cancel();
Task.WaitAll(tasks);
break;
}
else
{
if ((idx % 5) == 0)
{
DiagnosticHelper.DebugWriteLine(this.DisplayString() + " -> " + frType.ToString() + " -> Task.WaitAll, Waiting...");
}
}
idx++;
if (idx > 1000)
idx = 0;
} while (!Task.WaitAll(tasks, 1000));
// Wait for the tasks to cancel if they've not already completed
//Task.WaitAll(tasks);
}
catch (AggregateException aex)
{
aex.Handle(ex =>
{
// Handle the cancelled tasks
TaskCanceledException tcex = ex as TaskCanceledException;
if (tcex != null)
{
Debug.WriteLine("Handling cancellation of task {0}", tcex.Task.Id);
return true;
}
// Not handling any other types of exception.
return false;
});
}
// Show the state of each of the tasks.
// Some will be RanToCompletion, others will be Cancelled.
foreach (Task t in tasks.OrderBy(t => t.Id))
Debug.WriteLine("Tasks {0} state: {1}", t.Id, t.Status);
Debug.WriteLine("Program End");
}
No comments:
Post a Comment