Different ways to start a Task in C#

In this article, we will discuss different ways to start a task in C#

Earlier we have discussed on Threads and Tasks.You may read below articles for better understanding on Asynchronous Programming:

New threads can be started using the Task Programming Library in .NET.

You’ll first need to add the following using statement:

usingSystem.Threading.Tasks;

1. The most simple way to start a Task:

Task.Factory.StartNew(() => {Console.WriteLine("Hello World!"); });

2.Using Lambda and named method

Tasktask = new Task( () => PrintMessage() );
task.Start();

3.Using Lambda and anonymous method

Tasktask = new Task( () => { PrintMessage(); } );
task.Start();

4.Using Action

Tasktask = new Task(new Action(PrintMessage));
task.Start();
//where PrintMessage is a method:
private void PrintMessage()
{
    Console.WriteLine("Hello World!");
}

5.Using a delegate

Tasktask = new Task(delegate { PrintMessage(); });
task.Start();

6.Using Task.Run in .NET4.5

public asyncTaskDoWork()
{
    awaitTask.Run(() => PrintMessage());
}

7.Using Task.FromResult in .NET4.5 to return a result from a Task

public asyncTaskDoWork()
{
    int res = awaitTask.FromResult<int>(GetSum(22, 33));  
}
private int GetSum(int a, int b)
{
    return a + b;
}

Thanks for visiting !!

© 2016,admin. All rights reserved.

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章