Skip to content

SafeFireAndForget is not safe #65

@Szer

Description

@Szer

https://github.com/brminnick/AsyncAwaitBestPractices/blame/main/README.md#L140
This line says that:

`SafeFireAndForget` allows a Task to safely run on a different thread while the calling thread does not wait for its completion.

That couldn't be true, because implementation doesn't switch threads at all
https://github.com/brminnick/AsyncAwaitBestPractices/blob/d7ae1903f0a77913263a9bd81838faba70ef91a2/Src/AsyncAwaitBestPractices/SafeFireAndForgetExtensions.shared.cs#L77-L90

Everything prior first await will be executed on caller thread because that's how C# asyncs work (e.g. F# asyncs are different)

Code below will block caller thread for 5 sec before printing, which demonstrate that SafeFireAndForget isn't actually safe.

static async Task BadTask()
{
    Thread.Sleep(5000);
    await Task.CompletedTask;
}

static void Main(string[] args)
{
    BadTask().SafeFireAndForget();
    Console.WriteLine("Hello World!");
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is neededquestionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions