2012-04-25 71 views
1

我正在嘗試遵循類似於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.

回答

0

我在面對上面貼的是,所有的電子郵件將使用第一條消息的IP發送出了問題的問題。我認爲(可能是ServicePointManager正在緩存連接。儘管我還沒有找到重置ServicePointManager的解決方案,但是我意識到我在設置client = null;時的上述嘗試並沒有真正關閉連接,即使您很快撥打GC.Collect();也是如此。我發現工作的唯一的事情是:

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

總是發送每條消息後調用client.Dispose();重置連接,所以接下來的消息可以選擇IP地址,需要出去。

O. O.

+0

你可以將smtp客戶端包裝在一個使用中,並讓它爲你做。 (var client = new SmtpClient()){client.Send(msg); }' – 2013-09-19 14:20:51

1

我遇到了類似的問題,並希望重新ServicePointManager和更改證書爲不同的測試結果。我工作的方式是將MaxServicePointIdleTime設置爲較低的值,這將有效地重置它。

ServicePointManager.MaxServicePointIdleTime = 1;