【问题标题】:Is it possible to reset the ServicePointManager?是否可以重置 ServicePointManager?
【发布时间】:2016-07-20 00:58:55
【问题描述】:

我正在尝试遵循与How does System.Net.Mail.SMTPClient do its local IP binding 中给出的代码类似的代码,我在具有多个 IP 地址的机器上使用 Windows 7 和 .Net 4.0。我定义了BindIPEndPointDelegate

private static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
    string IPAddr = //some logic to return a different IP each time
    return new IPEndPoint(IPAddr, 0);
}

然后我使用

发送我的电子邮件
SmtpClient client = new SmtpClient();
client.Host = SMTP_SERVER; //IP Address as string
client.Port = 25;
client.EnableSsl = false;
client.ServicePoint.BindIPEndPointDelegate 
   = new System.Net.BindIPEndPoint(BindIPEndPointCallback);
client.ServicePoint.ConnectionLeaseTimeout = 0;
client.Send(msg);  //msg is of type MailMessage properly initialized/set
client = null;

第一次调用此代码时,将调用委托,并且无论设置什么 IP 地址,都会使用它。随后调用此代码时,委托永远不会被调用 ,即随后使用第一个 IP 地址。 是否可以改变这种每次调用代码时调用委托回调的情况?

我认为ServicePointManager(这是一个静态类)缓存了第一次调用委托的结果。可以重置这个类吗?我不在乎性能。

谢谢你, O.O.

【问题讨论】:

    标签: c# .net sockets email network-programming


    【解决方案1】:

    我遇到了类似的问题,想重置 ServicePointManager 并更改证书以获得不同的测试结果。对我有用的方法是将 MaxServicePointIdleTime 设置为一个较低的值,这将有效地重置它。

    ServicePointManager.MaxServicePointIdleTime = 1;
    

    【讨论】:

      【解决方案2】:

      我在上面发布的问题中遇到的问题是所有电子邮件都将使用第一条消息的 IP 发送出去。我认为某些(可能是 ServicePointManager 正在缓存连接。虽然我还没有找到重置 ServicePointManager 的解决方案,但我意识到我上面设置 client = null; 的尝试并没有真正关闭连接,即使您不久之后调用 GC.Collect();。我发现唯一有用的是:

      SmtpClient client = new SmtpClient();
      //Remaining code here.... 
      client.Send(msg); 
      client.Dispose(); //Secret Sauce
      

      发送每条消息后调用client.Dispose();总是会重置连接,因此下一条消息可以选择它需要发送的IP地址。

      哦。哦。

      【讨论】:

      • 您可以将 smtp 客户端包装在 using 中并让它为您执行此操作。 using(var client = new SmtpClient()) { client.Send(msg); }
      猜你喜欢
      • 2010-09-15
      • 2013-08-01
      • 1970-01-01
      • 2014-01-12
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多