Advertisement
ivandrofly

Getting a return value from a Task with C#

Mar 15th, 2014
678
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.96 KB | None | 0 0
  1. Getting a return value from a Task with C#
  2. Sometimes you want to get a return value from a Task as opposed to letting it run in the background and forgetting about it. You’ll need to specify the return type as a type parameter to the Task object: a Task of T.
  3. .NET 4.0
  4. Without specifying an input parameter:
  5. Task<int> task = new Task<int>(() =>
  6. {
  7.     int total = 0;
  8.     for (int i = 0; i < 500; i++)
  9.     {
  10.         total += i;
  11.     }
  12.     return total;
  13. });
  14.  
  15. task.Start();
  16. int result = Convert.ToInt32(task.Result);
  17. We count to 500 and return the sum. The return value of the Task can be retrieved using the Result property which can be converted to the desired type.
  18. You can provide an input parameter as well:
  19. Task<int> task = new Task<int>(obj =>
  20. {
  21.     int total = 0;
  22.     int max = (int)obj;
  23.     for (int i = 0; i < max; i++)
  24.     {
  25.         total += i;
  26.     }
  27.     return total;
  28. }, 300);
  29.  
  30. task.Start();
  31. int result = Convert.ToInt32(task.Result);
  32. We specify that we want to count to 300.
  33. .NET 4.5
  34. The recommended way in .NET 4.5 is to use Task.FromResult, Task.Run or Task.Factory.StartNew:
  35. FromResult:
  36.  
  37. public async Task DoWork()
  38. {
  39.        int res = await Task.FromResult<int>(GetSum(4, 5));    
  40. }
  41.  
  42. private int GetSum(int a, int b)
  43. {
  44.     return a + b;
  45. }
  46. Please check out Stefan’s comments on the usage of FromResult in the comments section below the post.
  47. Task.Run:
  48.  
  49. public async Task DoWork()
  50. {
  51.     Func<int> function = new Func<int>(() => GetSum(4, 5));
  52.     int res = await Task.Run<int>(function);
  53. }
  54.  
  55. private int GetSum(int a, int b)
  56. {
  57.     return a + b;
  58. }
  59. Task.Factory.StartNew:
  60.  
  61. public async Task DoWork()
  62. {
  63.     Func<int> function = new Func<int>(() => GetSum(4, 5));
  64.     int res = await Task.Factory.StartNew<int>(function);        
  65. }
  66.  
  67. private int GetSum(int a, int b)
  68. {
  69.     return a + b;
  70. }
  71. View the list of posts on the Task Parallel Library here.
  72. 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