Reputation: 2851
I have an array of subTasks, which execute a method, Once the job is completed I get a notification and its over. Now I want them to restart the same job again, without any hassle. How is this possible?
This is how I am creating the task array and working with task completion:
public void Start()
{
this.totalRangePerThread = ((this.endRange - this.startRange) / this.subTasks.Length);
for (int i = 0; i < this.subTasks.Length; ++i)
{
var copy = startRange;
this.subTasks[i] = new Task(() => searchItem(copy, this.totalRangePerThread), this.token, TaskCreationOptions.LongRunning);
this.startRange = this.startRange + this.totalRangePerThread;
}
//start tasks
for (int taskIndex = 0; taskIndex < this.subTasks.Length; ++taskIndex)
{
this.subTasks[taskIndex].Start();
}
Task.Factory.ContinueWhenAll(this.subTasks, completedTasks =>
{
//write it onto the the activitylog
if (Form1.Instance != null)
{
Form1.Instance.BeginInvoke((MethodInvoker)delegate
{
Form1.Instance.AddItemtoActivityLog("Search Completed!");
});
}
});
}
Should I make another call to the Start()
method or there is a mechanism that just magically restarts the subtasks?
Upvotes: 0
Views: 1914
Reputation: 3558
You can extract the code for preparing and executing subtasks to a separate method. Then call it twice in your Start()
method:
private void ExecuteSubTasks()
{
var tasks = new Task[]
{
new Task(() => Console.WriteLine("SubTask1 executed.")),
new Task(() => Console.WriteLine("SubTask2 executed.")),
new Task(() => Console.WriteLine("SubTask3 executed.")),
};
foreach (var task in tasks)
task.Start();
Task.WaitAll(tasks);
}
private void Start()
{
var mainTask = Task.Factory.StartNew(() => ExecuteSubTasks())
.ContinueWith((prev) =>
{
ExecuteSubTasks();
this.Invoke((MethodInvoker)delegate { MessageBox.Show("Completed."); });
});
}
Upvotes: 1
Reputation: 16277
public void Start()
{
var yourTasks = new Task[] {
Task.Factory.StartNew(_ => task1(),
Task.Factory.StartNew(_ => task2(),
Task.Factory.StartNew(_ => ...
Task.Factory.StartNew(_ => taskN() };
Task.WaitAll(yourTasks ); // wait for all N tasks to complete
Start();
}
Upvotes: 1