4

Trying to pass function instead lambda expression and finally mixed up why line:

int t2 = await Task.Run( ()=>Allocate2() ); 

not raises error. This lambda expression ()=>Allocate2() not returns Task. Why no error?

How to create task without lambda expression with function Allocate?

 static async void Example() { int t = await Task.Run(Allocate); int t2 = await Task.Run( ()=>Allocate2() ); Console.WriteLine("Compute: " + t); } static Task<int> Allocate() { return 1; } static int Allocate2() { return 1; } 
4
  • 3
    Task.Run return Task. What this task is doing inside is another story (see overloads). Commented Sep 25, 2017 at 12:07
  • running this I get this error Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task<int>' because your return type isnt matched. but what is it that you are trying to acheive. Commented Sep 25, 2017 at 12:12
  • I'm trying to run task without using lambda expression Commented Sep 25, 2017 at 12:13
  • why don't you make Allocate async and call var t = await Allocate(); Commented Sep 25, 2017 at 12:24

1 Answer 1

6

Task.Run() wants you to pass a parameterless Action or Func to it.

A lambda can be assigned to an Action or a Func (as appropriate) which is why calling Task.Run() with a lambda works for you.

If you don't want to use a lambda, you must explicitly create an Action or a Func, passing the method you want to call to the constructor of the Action or the Func.

The following demonstrates:

static void Main() { var task = Task.Run(new Action(MyMethod)); } static void MyMethod() { Console.WriteLine("MyMethod()"); } 

OR:

static void Main() { var task = Task.Run(new Func<int>(MyMethod)); } static int MyMethod() { Console.WriteLine("MyMethod()"); return 42; } 

Note that this doesn't work if the method needs one or more parameters. In that event, you must use a lambda.

Sign up to request clarification or add additional context in comments.

3 Comments

You could also perform an explicit cast as an alternative to newing.
How to use explicit cast in this case?
@vico You can cast it like so: var task = Task.Run((Func<int>)MyMethod); - but I don't really think that is an improvement. It actually ends up with more or less the same generated code. (See here for more info)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.