Chapter 1.3 C# – Tasks

Tasks are bits of code that do things and then waits for things to happen.

so we can have a few methods that can be created and then called to run as a task.

Task newTask = Task.Run(() -> DoWork());

This will create a new task and allow it to run to completion

Return a value from a task.

use the result code to get a return value from the function

static void Main(string[] args)
Task<int> task = Task.Run(() =>
return DoWork());

Wait for Tasks to complete

The Task.WaitAll method can be used to pause a program until a number of tasks are complete.

Task [] Tasks = new Task[10];

for (int i = 0; i < 10; i++)
int taskNum = i;
Tasks[i] = Task.Run( () => DoWork(taskNum) );


Task.Waitall is to provide a place where a program can catch any exceptions that might be thrown by tasks.