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?
(x, y) => Add(x, y)and two, there's no overload ofnew Task<T>that takes theFunc<int, int, int>you're trying to pass. That doesn't hurt, though - you can just capture the arguments directly -() => Add(5, 6). There really isn't much of a reason to pass the arguments in any other way...Task.Run(...)for long-running operations like disk- oder database-IO. See channel9.msdn.com/Series/Three-Essential-Tips-for-Async/… for a great overview.