c# - 在没有等待的情况下调用异步方法 - 潜在的处置对象问题

标签 c# asynchronous

我有一个 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();一样调用它

关于c# - 在没有等待的情况下调用异步方法 - 潜在的处置对象问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49172426/

相关文章:

c# - 如何创建解析器(lex/yacc)?

c# - 如何使用 TinyIOC 注册通用接口(interface)

c# - 知道插入符号在 Winforms TextBox 中的点位置?

c++ - 同步和异步 API

c# - 如何优化 "real-time"C#写文件和MATLAB读文件操作

android - Kotlin:元素未附加在列表中

c# - 为什么 Thread.Sleep 在其他应用程序运行时等待的时间比请求的时间长?

c# - Azure Rest api放置blob

node.js - 当前写入文件时如何处理 readFile

c# - HttpWebRequest 因异步和等待而随机失败