Lev Z
Lev Z

Reputation: 802

SmtpClient.SendAsync - Stop application after the call

I am building winforms application that has to send emails. I want to be able to call SmtpClient.SendAsync method and after that allow to user to close the app immediately (I am not interested to get sending results in callback function). If user stops application, the emails are not sended....If application stay running, the emails are sended as expected... Any suggestions, how can i pass all relevant details to smtp server and close my app?

Thanks

Upvotes: 0

Views: 525

Answers (1)

Douglas
Douglas

Reputation: 54897

Your operation needs to be allowed to execute until the delivery to the SMTP server is complete. If you really don't care about results, you could spawn a foreground thread to execute the delivery. This way, if the user closes the application, its GUI would be unloaded, but the foreground thread would persist until the operation completes. Once all foreground threads belonging to the process have terminated, the process itself would also terminate.

var t = new Thread(new ThreadStart(() => smtpClient.Send(message)));
t.IsBackground = false;
t.Start();

Edit: As CodeCaster has pointed out, this approach assumes that your application's process will keep running after the user closes its windows. The operation will fail if the user shuts down the system (or manually kills the process) before the thread has completed.

Upvotes: 3

Related Questions