Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Task without lambda

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;
    }
like image 357
vico Avatar asked Sep 19 '25 03:09

vico


1 Answers

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.

like image 66
Matthew Watson Avatar answered Sep 20 '25 17:09

Matthew Watson