Home > Net >  Start a concurrent async task from within another async task
Start a concurrent async task from within another async task

Time:08-02

I have an I/O-bound task implemented with an async-await function.

At some point in this function, I receive some information which allows me to start a concurrent task, which is also I/O-bound (and so it is also implemented with an async-await function). My original task is not bound by this new task - I just need to set it going in the background.

If I do the following, I get warned that I'm not awaiting the call. I don't want to await the call! I want it to happen in the background!

async Task AnotherAsyncThing()
{
}

async Task SomeAsyncThing()
{
    // ...

    // run concurrently - warning raised here
    Task.Run(async () => await AnotherAsyncThing());

    // ...
}

Am I missing something horribly obvious here? It feels like I am!

CodePudding user response:

You can do something like this:

_ = AnotherAsyncThing()

This is the discards feature added in C# 7.0 and is a way of communicating the fact you're not interested in the return value to the compiler.

CodePudding user response:

Yes and no :)

so often bugs occur when people forget to wait for tasks and it is considered a risk in APIs for instance to keep spinning up non awaited tasks because you can sometimes do so rapidly with bad performing client code and if that can steal many resources ... we'll i'm sure You can imagine.

But to signify that You know what You're doing and assume full responsibility, You can use the TPL like this and get rid of the warnings

_ = Task.Run(
        () => _ = AnotherAsyncThing()
    );

But each time this code is passed it will continue immediately and start something which will also continue to run. So Say your API gets a post, which accidentally happens every 10th millisecond instead of every 10th second as intended ... there is a danger in making the use of these things a standard.

It is a tool for a specific purpose, not the new white for walls, but yea You may have missed that we now should tell by using the nevermind underscore, that we know what we're doing this time and the compiler should back out from helping.

  • Related