Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Getting a return value from a Task with C#
- 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.
- .NET 4.0
- Without specifying an input parameter:
- Task<int> task = new Task<int>(() =>
- {
- int total = 0;
- for (int i = 0; i < 500; i++)
- {
- total += i;
- }
- return total;
- });
- task.Start();
- int result = Convert.ToInt32(task.Result);
- 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.
- You can provide an input parameter as well:
- Task<int> task = new Task<int>(obj =>
- {
- int total = 0;
- int max = (int)obj;
- for (int i = 0; i < max; i++)
- {
- total += i;
- }
- return total;
- }, 300);
- task.Start();
- int result = Convert.ToInt32(task.Result);
- We specify that we want to count to 300.
- .NET 4.5
- The recommended way in .NET 4.5 is to use Task.FromResult, Task.Run or Task.Factory.StartNew:
- FromResult:
- public async Task DoWork()
- {
- int res = await Task.FromResult<int>(GetSum(4, 5));
- }
- private int GetSum(int a, int b)
- {
- return a + b;
- }
- Please check out Stefan’s comments on the usage of FromResult in the comments section below the post.
- Task.Run:
- public async Task DoWork()
- {
- Func<int> function = new Func<int>(() => GetSum(4, 5));
- int res = await Task.Run<int>(function);
- }
- private int GetSum(int a, int b)
- {
- return a + b;
- }
- Task.Factory.StartNew:
- public async Task DoWork()
- {
- Func<int> function = new Func<int>(() => GetSum(4, 5));
- int res = await Task.Factory.StartNew<int>(function);
- }
- private int GetSum(int a, int b)
- {
- return a + b;
- }
- View the list of posts on the Task Parallel Library here.
- 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