1

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?

2
  • There's two basic mistakes - one, defining an anonymous delegate with multiple arguments requires you to use parentheses, e.g. (x, y) => Add(x, y) and two, there's no overload of new Task<T> that takes the Func<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... Commented Jun 11, 2015 at 12:55
  • There is also a common misconcept with the Task-Framework: Tasks do not necessarily use multithreading! You may need 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. Commented Jun 11, 2015 at 14:02

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

9 Comments

Error 1 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
Error 2 'System.Threading.Tasks.Task' does not contain a definition for 'Run' C:\Program.cs
Yes, you'd need to add async to the enclosing method (as it suggests) in order to use await. You might want to read this blog post (and many more on that blog!). Task.Run is available in .NET 4.5 - what are you using?
.NET 4.5.5.. how do I add async to the enclocing method?
That's a start, but by using Result you're just blocking while you wait for the other thread which sort of renders it a bit pointless.
|
0
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 });

2 Comments

-Error 3 Argument 1: cannot convert from 'int[]' to 'System.Threading.Tasks.TaskScheduler' -Error 2 The best overloaded method match for 'System.Threading.Tasks.Task.Start(System.Threading.Tasks.TaskScheduler)' has some invalid arguments -Error 1 Delegate 'System.Func<int>' does not take 1 arguments
@user3037960 Sorry again !! I was not using Visual Studio and writing manually. Try now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.