通过 C# 发送的电子邮件在没有 Console.ReadLine 的情况下无法发送

问题描述 投票:0回答:1

我发现有一个从 Windows 服务器发送电子邮件的例程。这基本上是我试图弄清楚的代码:

// Set the method that is called back when the send operation ends.
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

// The userState can be any object that allows your callback
// method to identify this send operation.
// For this example, the userToken is a string constant.
string userState = "test message1";
client.SendAsync(message, userState);
Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
string answer = Console.ReadLine();

如果我删除最后一行 -

Console.ReadLine()
- 电子邮件不会发送。看来我需要延迟(1-3 秒?)才能完成
client.SendAsync()

是否还需要其他设置才能让

client.SendAsync()
等待发送后再返回?或者使用其他方法?第一次尝试发送电子邮件,我正在努力解决这个问题。

感谢您提供的任何帮助/指导。

c# email delay smtpclient sendasync
1个回答
0
投票

由于您没有提供完整的代码,我将不得不假设您的应用程序在

Console.ReadLine()
命令之后结束。您在此之前启动了
SendAsync
功能。

按照一般逻辑,可以推断

SendAsync
函数是一个 async function 。当主线程开始执行更多代码行时,这些函数在后台执行。因此,在没有
Console.ReadLine()
的情况下,您将在后台启动
SendAsync
功能,然后在
SendAsync
功能完成之前立即退出应用程序。

您可以通过包含 await 运算符来解决此问题,如下所示:

await client.SendAsync(message, userState);

© www.soinside.com 2019 - 2024. All rights reserved.