小编Er *_*tel的帖子

发送批量电子邮件时出错"异步调用已在进行中.必须先完成或取消,然后才能调用此方法"

我创建了一个控制台应用程序,用于将数据从一个数据库表迁移到另一个数据库表,其中迁移了客户的记录,因此我必须通知他们密码更改.

public static async Task<bool> SendRegisterEmail(List<MailMessage> mailMessage)
{
    bool flag = true;
    try
    {
        var smtp = new SmtpClient();
        var taskEmails = mailMessage.Select(x => smtp.SendMailAsync(x));

        await Task.WhenAll(taskEmails); // **Error : An asynchronous call is already in progress. It must be completed or canceled before you can call this method**
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return flag;
}
Run Code Online (Sandbox Code Playgroud)

如果我删除了等待Task.WhenAll(taskEmails),但是当迁移操作完成时,它不会发送所有电子邮件.操作完成后关闭的控制台应用程序中有许多仍未发送,我有超过1,00,000条记录,那么如何在后台或应用程序运行中继续发送电子邮件,直到所有电子邮件成功发送?

以下是数据迁移的代码:

foreach (DataRow SourceReader in DS.Tables[0].Rows)
{
    insertCounter++;
    using (SqlCommand DestinationCommand = DestinationConnection.CreateCommand())
    {
        Console.WriteLine("inserting row...");
        var …
Run Code Online (Sandbox Code Playgroud)

c# asynchronous console-application smtpclient

3
推荐指数
1
解决办法
1743
查看次数