1
votes

I have following Scenario,

public class User
{
    public static async Task<bool> UserRegistration()
    {
        // So Many Async Async Await Methods 
        bool IsRegistrationSuccess = await RegisterUser();

        if(IsRegistrationSuccess)
        {
            await SendSMS();    // Fire And Forget
            await SendEmail();  // Fire And Forget
            return true;
        }
        return false;
    }

    private static async Task SendSMS()
    {
        string URL = "http://www.example.com/dsad";
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(URL);
        }
    }

    private static async Task SendEmail()
    {
        string emailMessage = "Some Email";
        await EmailService.Send(emailMessage);
    }
}

I want to call SendSMS(); and SendEmail(); without await. Don't want to wait for the result. If I do So gives the warning,

because this call is not awaited execution of the current method continues before the call is completed. Consider applying an operator to the result of the call.

So, question is, If the UserRegistration() method returns before completion of SendSMS() OR SendEmail(), Does it fire the exception? And Is it good practice to make Fire and Forget call in Async Await Methods?

1
Ignoring the fact you are showing wrong fire and forget, it is very strange that you don't care if all those methods fail... Are you sure that's what you want?Alexei Levenkov
the bad thing is that user registration can fail but e-mail will be sent (if not awaited) that can be frustrating. I suppose that email should notify me about user registration result, not about user registration attempt.oleksa
@oleksa I have updated code If Registration Success then only these methods will get called.Sushant Yelpale
look, but if not await for UserRegistration (fire and forget it) how can you know that it was succeed (or not)? This is the point actually.oleksa
I see thank you. But do you have some error handling for the email or sms sending methods ? It does not matter how do you creates those fire and forget using threads or async methods. So I think it is fine. The only one problem if anyone will find this warning and decide to "fix" it by adding the async. It is better to use the @gldraphael suggestion to hide the warningoleksa

1 Answers

2
votes

It's just a warning, so that you know it's not been awaited on. You can use discard to make it clear you don't care whether or not it ends up running to completion:

_ = SendSMS();

So, question is, If the UserRegistration() method returns before completion of SendSMS() OR SendEmail(), Does it fire the exception?

Nope.

And Is it good practice to make Fire and Forget call in Async Await Methods?

Not in my opinion.