Advertisement
ivandrofly

7 ways to start a Task in .NET C#

Mar 15th, 2014
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.31 KB | None | 0 0
  1. 7 ways to start a Task in .NET C#
  2.  
  3. New threads can be started using the Task Programming Library in .NET in – at last – 5 different ways.
  4. You’ll first need to add the following using statement:
  5. using System.Threading.Tasks;
  6.  
  7. The most direct way
  8. Task.Factory.StartNew(() => {Console.WriteLine("Hello Task library!"); });
  9.  
  10. Using Action
  11. Task task = new Task(new Action(PrintMessage));
  12. task.Start();
  13.  
  14. where PrintMessage is a method:
  15. private void PrintMessage()
  16. {
  17.     Console.WriteLine("Hello Task library!");
  18. }
  19.  
  20. Using a delegate
  21. Task task = new Task(delegate { PrintMessage(); });
  22. task.Start();
  23.  
  24. Lambda and named method
  25. Task task = new Task( () => PrintMessage() );
  26. task.Start();
  27.  
  28. Lambda and anonymous method
  29. Task task = new Task( () => { PrintMessage(); } );
  30. task.Start();
  31.  
  32. Using Task.Run in .NET4.5
  33. public async Task DoWork()
  34. {
  35.     await Task.Run(() => PrintMessage());
  36. }
  37.  
  38. Using Task.FromResult in .NET4.5 to return a result from a Task
  39. public async Task DoWork()
  40. {
  41.     int res = await Task.FromResult<int>(GetSum(4, 5));  
  42. }
  43.  
  44. private int GetSum(int a, int b)
  45. {
  46.     return a + b;
  47. }
  48. You cannot start a task that has already completed. If you need to run the same task you’ll need to initialise it again.
  49. 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