0

I feel like there is a better way to do the following and looking for other opinions.

Essentially, I am trying to utilize the async/await pattern but need to return a bool value from method to indicate what happened in the method which is causing me to wrap the Task with Task so this can be accomplished. My spidey-sense is telling me something is wrong with my implementation.

In the below example "LongRunningTask" is something I don't have control over because it is a library method that returns a Task, so something I can't change. The remainder of the flow logic could be changed. Obviously, this is just a fictional representation of my real-issue but meant to demonstrate the issue, so don't get caught-up in the hard-coded "GetData", etc...

Take a look and let me know of other options.

void Main()
{
    StartApplication();
}

private async void StartApplication()
{
    // This is a just fictional example passing hard-coded GetData
    var didExecuteLongRunningTask = await ProcessStuff("GetData");

    if (didExecuteLongRunningTask)
    {
        Console.WriteLine("Long running task was executed");
    }
    else {
        Console.WriteLine("Long running task was NOT executed");
    }
}

// Define other methods and classes here
private async Task<bool> ProcessStuff(string command)
{
    if (command == "GetData")
    {
        await LongRunningTask();
        return await Task<bool>.Factory.StartNew(() => true);
    }
    else
    {
        return await Task<bool>.Factory.StartNew(() => false);
    }
}

private Task LongRunningTask()
{
    return Task.Delay(2000);
}
1
  • 3
    your function is marked async just do return true; or return false; Commented May 28, 2017 at 20:16

1 Answer 1

2

Yes, you are right, you are over-complicating it. You can just do:

private async Task<bool> ProcessStuff(string command)
{
    if (command == "GetData")
    {
        await LongRunningTask();
        return true;
    }
    else
    {
        return false;
    }
}

You can look at the MSDN for more information: Asynchronous Programming

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

3 Comments

Wow, ok... I didn't even try that as I didn't realize returning bool would magically get converted to Task<bool>. I'll have to research how that works...
@JoshuaMason you can get all the basics from the MSDN link I posted
Thank you, I've actually been using async/await pattern for quite some time, but somehow missed this completely. This article actually explains the magic of this particular aspect fairly well. learn.microsoft.com/en-us/dotnet/csharp/programming-guide/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.