Reputation: 3613
Given function:
private static int Add(int x, int y)
{
Console.WriteLine("Add() invoked on thread {0}.",
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
return x + y;
}
I tried this:
Task<int> t = new Task<int>(x, y => Add(x, y), 5, 6); // 5+6
t.Start();
t.Wait();
// Get the result (the Result property internally calls Wait)
Console.WriteLine("The sum is: " + t.Result);
It cant be compiled, obviously. How do I do this correctly?
Upvotes: 1
Views: 3069
Reputation:
Task<int> t = new Task<int>(x, y => Add(x, y), 5, 6); // 5+6
What are you trying to do is to define a Task that takes parameters, and passes these parameters to its inner code.
You can use the overload which takes an object
parameter to pass values, like this:
Task<int>.Factory.StartNew(obj => {
var arr = obj as int[];
return arr[0] + arr[1];
}, new[] { 5, 4 });
Upvotes: 0
Reputation: 26213
First, I'd use Task.Run
instead of explicitly creating a new Task
. Then I'd await
the result rather than blocking until it is completed. This will require the enclosing method to be marked async
- you can read more about async/await in this blog post. I'd suggest reading many more on that blog.
You can capture your arguments as part of the lambda expression. This part is the reason why your current code doesn't compile. This is generally more useful than the Action<object>
overload in the Task
constructor. The end result:
private static async Task AddAsync()
{
var result = await Task.Run(() => Add(5, 6));
Console.WriteLine("The sum is: {0}", result);
}
Upvotes: 3