The Task in .net is kind of a thread. A Task object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread. Most commonly, a lambda expression is used to specify the work that the task is to perform. The action here defines a Lambda expression.
using System;
using System.Threading;
using System.Threading.Tasks;
class Example
{
static void Main()
{
Action<object> action = (object obj) =>
{
Console.WriteLine("Task={0}, obj={1}, Thread={2}",
Task.CurrentId, obj,
Thread.CurrentThread.ManagedThreadId);
};
// Create a task but do not start it.
Task t1 = new Task(action, "alpha");
// Launch t1
t1.Start();
// Wait for the task to finish.
t1.Wait();
}
}
Task can be created in a few ways. The Run method provides a simple way to start a task using default values and without requiring additional parameters.
Here it runs the lambda expression straight away.
using System;
using System.Threading.Tasks;
public class Example
{
public static async Task Main()
{
await Task.Run( () => {
// Just loop.
int ctr = 0;
for (ctr = 0; ctr <= 1000000; ctr++)
{}
Console.WriteLine("Finished {0} loop iterations",
ctr);
} );
}
}
wait() vs await
The Task.wait() and await are concetually achieving the same thing, i.e. wait until the task finishes. However their implementations are different as per stackoverflow.
Wait will synchronously block until the task completes. So the current thread is literally blocked waiting for the task to complete.
await will asynchronously wait until the task completes. This means the current method is "paused" (its state is captured) and the method returns an incomplete task to its caller. Later, when the await expression completes, the remainder of the method is scheduled as a continuation.
The 'async' keyword here with the Main() method just specify the method as asynchronous, so the method can use await within it. Otherwise it won't be able to use await.
Note the Main() method now needs to return Task or Task<T> (i.e. Task Main()) to be able to run as async. Previously, before vs 2017, async Main() was not allowed because the await doesn't block so it can return from a console app which is an exit of the program. Later the compiler supports 'async Task Main()' by specifying the Task return value.
Another way is to use Task.Factory.
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
Task t = Task.Factory.StartNew( () => {
// Just loop.
int ctr = 0;
for (ctr = 0; ctr <= 1000000; ctr++)
{}
Console.WriteLine("Finished {0} loop iterations",
ctr);
} );
t.Wait();
}
}