簡體   English   中英

觸發並忘記異步等待調用

[英]Fire and Forget Async Await Call

我有以下場景,

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);
    }
}

我想打電話給SendSMS(); SendEmail(); 無需等待。 不想等結果。 如果我這樣做,那么會發出警告,

因為此調用未等待當前方法的執行在調用完成之前繼續執行。 考慮將運算符應用於調用結果。

所以,問題是,如果UserRegistration()方法在SendSMS()SendEmail()完成之前返回,它是否會觸發異常? 在 Async Await 方法中進行 Fire and Forget 調用是一種好習慣嗎?

這只是一個警告,所以你知道它沒有被await 您可以使用丟棄來明確表示您不關心它是否最終運行完成:

_ = SendSMS();

所以,問題是,如果 UserRegistration() 方法在 SendSMS() 或 SendEmail() 完成之前返回,它是否會觸發異常?

不。

在 Async Await 方法中進行 Fire and Forget 調用是一種好習慣嗎?

在我看來不是。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM