Introduction
Tasks are created and maintained explicitly by developers. Developers can control the tasks or process the return values. So, they have control over the the behavior of Task. Microsoft provides bunch of methods to control current Tasks.
Below are the methods which are being used to control current Task:
Start()
It starts the task and schedules for the execution.
Example
- public void StartTask()
- {
- Task<int> task = new Task<int>(obj =>
- {
- int myTotal= 0;
- int max = (int)obj;
- for (int i = 0; i < max; i++)
- {
- myTotal += i;
- }
- return myTotal;
- }, 400);
-
- task.Start();
-
- int result = Convert.ToInt32(task.Result);
- Console.WriteLine("Total {0}", result);
- }
So, here task.Start() method will start the task and we specified that we want result from 0 to 400.
Wait()
It waits for the Task to complete execution. It is a synchronization method that causes the calling thread to wait until the current task has completed.
Below are the reasons for which we will apply Wait() method:
- If main thread depends on the final result completed by the given Task.
- If you want to handle exception that might be thrown by Tasks.
Below are the some methods of wait:
- public void TaskWithWait()
- {
- var parent = Task.Factory.StartNew(() =>
- {
- Console.WriteLine("Main Task Started...");
- for (int value = 0; value < 10; value++)
- {
- int myTaskNo = value;
- Task.Factory.StartNew((x) =>
- {
- Console.WriteLine("Child Task {0} completed.",
- x);
- },
- myTaskNo, TaskCreationOptions.AttachedToParent);
- }
- });
-
- parent.Wait();
- Console.WriteLine("Main task completed.");
- }
Output:
Main Task Started...
Child Task 9 Completed.
Child Task 0 Completed.
Child Task 8 Completed.
Child Task 1 Completed.
.......................................
Main Task Completed...
So, here Main Task did wait for the complete of Child Task.
WaitAll
It is used to block all tasks to complete.
Example:- Task[] tasks = new Task[3]
- {
- Task.Factory.StartNew(() => MyMethodA()),
- Task.Factory.StartNew(() => MyMethodB()),
- Task.Factory.StartNew(() => MyMethodC())
- };
-
- Task.WaitAll(tasks);
ContinueWith()
It starts new task after the complete status of current task.
Example:
- public void TaskContinueWith()
- {
-
- Task<DayOfWeek> myTask = new Task<DayOfWeek>(() => DateTime.Today.DayOfWeek);
-
-
- Task<string> continuation = myTask.ContinueWith((antecedent) =>
- {
- return String.Format("Today is {0}.", antecedent.Result);
- });
-
- taskA.Start();
-
- Console.WriteLine(continuation.Result);
- }
Output
Today is Friday.
RunSynchronously()
By Default Task runs asynchronously. But, this method runs Task synchronously. For more details about RunSynchronously() method of Task please visit the
following link.
Conclusion
So, these methods provide way to control Task. Developer can easily control the Task as per requirements.
Read more articles on Multithreading: