Task in .NET C#
New threads can be started using the
Task Programming Library in .NET in – at last – 5 different ways.
You’ll first need to add the
following using statement:
using System.Threading.Tasks;
|
1. The
most direct way
Task.Factory.StartNew(() => Console.WriteLine("Task
library Sample!"));
|
2. Using
Action
|
Task task = new
Task(new Action(PrintMessage));
task.Start();
|
…where PrintMessage is a method:
|
private static
void PrintMessage()
{
Console.WriteLine("Hello Task
library!");
}
|
3. Using
a delegate
|
Task task = new
Task(delegate
{ PrintMessage(); });
task.Start();
|
4. Lambda
and named method
|
Task task = new
Task(() => PrintMessage());
task.Start();
|
5. Lambda
and anonymous method
|
Task task = new
Task(() => { PrintMessage(); });
task.Start();
|
6. Using
Task.Run in .NET4.5
|
{
await Task.Run(() =>
PrintMessage());
}
|
7. Using
Task.FromResult in .NET4.5 to return a result from a Task
|
public async Task DoWork()
{
int
res = await
Task.FromResult<int>(GetSum(4, 5));
}
private int GetSum(int a, int b)
{
return a + b;
}
|
You cannot start a task that has
already completed. If you need to run the same task you’ll need to initialise
it again.
No comments:
Post a Comment