2

我正在尝试在SmtpClient.SendMailAsync具有 32 个 CPU 的 Windows Server 2008 64 位企业版上使用 .NET 4.5 的方法发送大量电子邮件。

在调试过程中,我发现只有两个请求同时运行。考虑到我在服务器操作系统上,这很奇怪。

这是一个简单的测试用例:

static void Main(string[] args)
{
    var sw = Stopwatch.StartNew();
    var t1 = SendEmail();
    var t2 = SendEmail();
    var t3 = SendEmail();
    var t4 = SendEmail();
    var t5 = SendEmail();
    var t6 = SendEmail();
    var t7 = SendEmail();
    var t8 = SendEmail();
    Task.WaitAll(t1, t2, t3, t4, t5, t6, t7, t8);
    Console.WriteLine(sw.Elapsed);
}

static async Task SendEmail()
{
    using (var smtp = new SmtpClient())
    {
        Console.WriteLine("Starting [{0}]", DateTime.UtcNow.ToString("o"));
        await smtp.SendMailAsync("...", "...", "Test", "Testing...");
        Console.WriteLine("Done [{0}]", DateTime.UtcNow.ToString("o"));
    }
}

和结果。它开始很快,但分两批完成(见时代)。在 Process Explorer 中检查打开的连接也显示了相同的行为。

Starting [2013-03-07T14:27:17.4643296Z]
Starting [2013-03-07T14:27:17.4783382Z]
Starting [2013-03-07T14:27:17.4783382Z]
Starting [2013-03-07T14:27:17.4793387Z]
Starting [2013-03-07T14:27:17.4793387Z]
Starting [2013-03-07T14:27:17.4793387Z]
Starting [2013-03-07T14:27:17.4793387Z]
Starting [2013-03-07T14:27:17.4793387Z]
Done [2013-03-07T14:27:19.2070974Z]
Done [2013-03-07T14:27:19.2070974Z]
Done [2013-03-07T14:27:19.7541596Z]
Done [2013-03-07T14:27:19.7602234Z]
Done [2013-03-07T14:27:20.3880420Z]
Done [2013-03-07T14:27:20.3906050Z]
Done [2013-03-07T14:27:20.9254624Z]
Done [2013-03-07T14:27:20.9324577Z]
00:00:03.7476343

有没有办法真正启动更多请求?

4

1 回答 1

3

每个 ServicePoint 对象的默认限制为 2 个并发连接。您可以通过设置 ServicePointManager.DefaultConnectionLimit 为未来的 ServicePoint 实例修改此设置。您还可以修改现有实例的 ServicePoint.ConnectionLimit - SmtpClient 公开了一个 ServicePoint 属性,您可以使用该属性来获取它。

于 2013-03-07T16:00:55.647 回答