Asynchronously sending Emails in C#?

后端 未结 10 1406
礼貌的吻别
礼貌的吻别 2020-11-28 23:43

I\'m developing an application where a user clicks/presses enter on a certain button in a window, the application does some checks and determines whether to send out a coupl

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 00:12

    Here is a fire and forget approach together with async using .Net 4.5.2+:

    BackgroundTaskRunner.FireAndForgetTaskAsync(async () =>
    {
        SmtpClient smtpClient = new SmtpClient(); // using configuration file settings
        MailMessage message = new MailMessage(); // TODO: Initialize appropriately
        await smtpClient.SendMailAsync(message);
    });
    

    where BackgroundTaskRunner is:

    public static class BackgroundTaskRunner
    {     
        public static void FireAndForgetTask(Action action)
        {
            HostingEnvironment.QueueBackgroundWorkItem(cancellationToken => // .Net 4.5.2+ required
            {
                try
                {
                    action();
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                }
            });
        }
    
        /// 
        /// Using async
        /// 
        public static void FireAndForgetTaskAsync(Func action)
        {
            HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken => // .Net 4.5.2+ required
            {
                try
                {
                    await action();
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                }
            });
        }
    }
    

    Works like a charm on Azure App Services.

提交回复
热议问题