Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 7 ways to start a 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;
- The most direct way
- Task.Factory.StartNew(() => {Console.WriteLine("Hello Task library!"); });
- Using Action
- Task task = new Task(new Action(PrintMessage));
- task.Start();
- …where PrintMessage is a method:
- private void PrintMessage()
- {
- Console.WriteLine("Hello Task library!");
- }
- Using a delegate
- Task task = new Task(delegate { PrintMessage(); });
- task.Start();
- Lambda and named method
- Task task = new Task( () => PrintMessage() );
- task.Start();
- Lambda and anonymous method
- Task task = new Task( () => { PrintMessage(); } );
- task.Start();
- Using Task.Run in .NET4.5
- public async Task DoWork()
- {
- await Task.Run(() => PrintMessage());
- }
- 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.
- Found in: http://dotnetcodr.com/2014/01/01/5-ways-to-start-a-task-in-net-c/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement