是否可以重置 ServicePointManager?

O.O*_*.O. 2 .net c# sockets email network-programming

我正在尝试遵循类似于System.Net.Mail.SMTPClient 如何执行其本地 IP 绑定中给出的代码我在具有多个 IP 地址的计算机上使用 Windows 7 和 .Net 4.0。我定义了BindIPEndPointDelegate

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

然后我使用发送电子邮件

\n\n
SmtpClient client = new SmtpClient();\nclient.Host = SMTP_SERVER; //IP Address as string\nclient.Port = 25;\nclient.EnableSsl = false;\nclient.ServicePoint.BindIPEndPointDelegate \n   = new System.Net.BindIPEndPoint(BindIPEndPointCallback);\nclient.ServicePoint.ConnectionLeaseTimeout = 0;\nclient.Send(msg);  //msg is of type MailMessage properly initialized/set\nclient = null;\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

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

\n\n

谢谢你,\nO。奥。

\n

小智 5

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

ServicePointManager.MaxServicePointIdleTime = 1;
Run Code Online (Sandbox Code Playgroud)