Returning Task<bool> that involves a pending Task

dg2k 1,386 Reputation points
2022-08-20T23:29:11.84+00:00

I never went beyond returning Task.FromResult(computedValue) in my asynchronous programming.
I was wondering if it is possible to return a Task even when computedValue is yet to be determined from another pending Task as illustrated below.

THE EASY ONE:

public Task<bool> IsFileNameExists(string fileName)  
{  
    bool isFileExists = CheckIfFileNameExists(fileName);  
  
    return Task.FromResult(isFileExits );  
}  

THE NOT EASY:

public Task<bool> IsFileNameExists(string fileName)  
{  
    var objectResult = Database.Table<DataEntriesModel>().Where(x => x.FileName == fileName).FirstOrDefault(); // this is returning Task  
  
    // What I want to return is CompletedTask result is not null.  
    // I cannot use the following because objectResult is a pending, and pending Task is not null even if completed task is null  
    // and objectResult != null will always be true.  
  
    return Task.FromResult(objectResult != null);  
}  

Yes, I can make the method async Task<bool> and return an awaited result.
I just wondered if Task<bool> can still be returned when the <bool> evaluation is dependent on a pending Task.
Can this be done and how?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,245 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 112.1K Reputation points
    2022-08-21T18:47:54.707+00:00

    Check if this works:

    public Task<bool> IsFileNameExists(string fileName)  
    {  
       return Task.Run( () => Database.Table<DataEntriesModel>().Where(x => x.FileName == fileName).FirstOrDefault() != null);  
    }  
    

  2. Michael Taylor 48,281 Reputation points
    2022-08-22T14:54:00.363+00:00

    You can do the waiting in the caller if you really want to but I don't know that I'd recommend that approach. But honestly your method isn't doing anything that needs additional work so there shouldn't be any awaiting needed at all.

       public async Task<bool> IsFileNameExists(string fileName)  
       {  
            var objectResult = await Database.Table<DataEntriesModel>().Where(x => x.FileName == fileName).FirstOrDefault(); // this is returning Task  
                 
            return objectResult != null;  
       }  
    

    But if you wanted to do this in the caller then you'd do something like this.

       bool result = Database.Table<...>.Where().FirstOrDefault()  
                                  .ContinueWith(x => x != null);  
    

    But the problem I'm having is that neither Where nor FirstOrDefault are async. Therefore I don't see where in this line of code you are actually using async logic. If Table<> where to return an async object then the Where call would be invalid. Hence your first line of code is actually just synchronous.