簡體   English   中英

不等待就調用異步方法-潛在的對象問題

[英]Calling an async method without await - potential for disposed object problems

我有一個winforms應用程序,用戶可以從中發送電子郵件。 這封電子郵件是異步發送的,沒有等待(即發即忘)

調用電子郵件異步的方法實例化一個類(EmailSender),該類完成撰寫電子郵件,發送電子郵件並將結果記錄到數據庫中的所有工作。 我希望將EmailSender封裝在using語句中會造成資源仍然無法正常工作而試圖完成的問題。 但是,如果僅實例化該類並調用EmailSender.Send(),則資源將無法正確處理。

在仍然正確管理資源的同時,進行此操作的最佳方法是什么。 我最好將所有這些都放到管理自己資源的靜態方法中,還是我完全誤解了這里的問題

//Fire and forget
EmailSender es = new EmailSender(itemId);
es.Send();



public class EmailSender
{

    public EmailSender(int ItemId)
    {
        //initialise stuff
    }

    public async void SendAsync()
    {
        string emailContent = getEmailContent();
        using (MailMessage mail = new MailMessage())
        {
            using (SmtpClient client = emailManager.getSMTPSettings())
            {
                try
                {
                    string fromSender = emailManager.getEmailFrom();
                    if (!string.IsNullOrEmpty(fromSender)) mail.From = new MailAddress(fromSender);
                    //etc
                    await client.SendMailAsync(mail);
                }
                catch
                { //log to db}
                }
            }
        }
    }

    private string getEmailContent()
    {
        return "content";
    }
}

編輯:我希望異步代碼在窗體關閉后繼續在后台運行,並且用戶移至應用程序的不同部分。

如果異步方法返回Task ,則可以像SendAsync().Wait();一樣調用它SendAsync().Wait();

暫無
暫無

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

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