Comparison operator between asynchronous functions

I have two asynchronous function which returns boolean value after doing some complex calculations as below.

Function 1:

public Task<bool> function1()
{   
      //do some calculation and gives boolean value
      return Task.FromResult(true);
}

Function 2:

public Task<bool> function2()
{   
      //do some calculation and gives boolean value
      return Task.FromResult(false);
}

And I want to use comparison operator between these two functions as below.

public async Task<bool> function2()
{   
     return await function1() && await function2();
}

Is this a good approach to use comparison operator (and, or) between two asynchronous function. If not how can we do this in a better way?

1 answer

  • answered 2021-05-05 10:39 SomeBody

    There are two ways how to call this. The first one is the one that you presented:

    public async Task<bool> function2()
    {   
       return await function1() && await function2();
    }
    

    This means: function1() is executed, and when it's finished, then function2() is executed. But your method is async, so maybe you want to execute them concurrently? In that case, you have to call it the following way:

    public async Task<bool> function2()
        {   
           var result1 = function1();
           var result2 = function2();
           return await result1 && await result2;
        }