2012-04-25 87 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;