Async method to return true or false in a Task

I know that an async method can only return void or Task. I have read similar methods for Exception handling inside async methods. And I'm new to async programming so I am looking for a straightforward solution.

My async method runs an Sql query. If the query was ok, it should notify the caller with a Boolean true and otherwise a false. My method is currently a void so I have no way of knowing.

private async void RefreshContacts()
{
    Task refresh = Task.Run(() =>
    {
        try
        {
            // run the query
        }
        catch { }
    }
    );
    await refresh;           
}

I simply would like to change async to Task so that in my catch statement the method will return a false and otherwise a true.

Jon Skeet
people
quotationmark

It sounds like you just need to return a Task<bool> then:

private async Task<bool> RefreshContactsAsync()
{
    try
    {
        ...
    }
    catch // TODO: Catch more specific exceptions
    {
        return false;
    }
    ...
    return true;
}

Personally I would not catch the exception, instead letting the caller check the task for a faulted state, but that's a different matter.

people

See more on this question at Stackoverflow