我正在嘗試遵循類似於How does System.Net.Mail.SMTPClient do its local IP binding給出的代碼我在具有多個IP地址的計算機上使用Windows 7和.Net 4.0。我有BindIPEndPointDelegate定義是否可以重置ServicePointManager?
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.
你可以將smtp客戶端包裝在一個使用中,並讓它爲你做。 (var client = new SmtpClient()){client.Send(msg); }' – 2013-09-19 14:20:51