我正在尝试在具有32个CPU的Windows Server 2008 64位Enterprise上使用.NET 4.5中的SmtpClient.SendMailAsync方法发送一堆电子邮件。

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

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

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


有没有办法真正增加更多请求?

最佳答案

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

10-04 19:19