服务用尽TCP连接 [英] Service running out of TCP connections
问题描述
我有一个Windows服务,它是使用c#.net 4.0创建的,它是一些事情的监视器-它上面有一个计时器,并且它有一个计时器,每5分钟运行一次.因此它具有计时器控件,并且计时器中有一个Elapsed事件:
I have a windows service, created using c# .net 4.0, which is a monitor for a few things - it has a timer on it, and it has a timer to run it every 5 mins. So it has a timer control, and in the timer there is a Elapsed event:
private void Timer_Elapsed(object sender, System.Events.ElapsedEventArgs e)
{
FileMonitor fileMon = new FileMonitor(url);
}
发生的事情是,在FileMonitor中,它使用TfsTeamProjectCollection类与TFS服务器项目建立了连接,
Whats happening is that in FileMonitor, its making a connection to a TFS server project, using the TfsTeamProjectCollection class as such:
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(url, new NetworkCredential( username, password, domain);
正在发生的事情是,我认为这会在方法Timer_Elapsed结束后立即自动关闭连接,但似乎没有,并且服务器用尽了TCP连接,其他服务无法再连接
What's happening is that I thought that this would automatically close the connection as soon as the method Timer_Elapsed ended, but it doesn't seem to, and the server is running out of TCP connections, and other services can't connect anymore.
所以我的问题有两个:
- In a windows service, if I instantiate a new class, it gets destroyed as soon as the method ends, right?
- In this case, I've read that TfsTeamProjectCollection doesn't close the connection really: http://social.msdn.microsoft.com/Forums/vstudio/en-US/a0878218-d8dd-4c2a-916f-00bc5b3be2da/tfsteamprojectcollectiondisconnect-missing- - and if thats the case, what is a better way to handle this than what is suggested in that post?
总体而言,使用FileMonitor时我应该对服务本身做些什么-应该手动销毁它,还是让垃圾回收销毁它?
Overall, what should I do for the service itself when using FileMonitor - should I be destroying it manually, or let garbage collection destroy it?
推荐答案
- 不,不是
- 可以调用
Disconnect
,或者最好还是使用using
关键字.
- No it doesn't
- Either call
Disconnect
, or better still use theusing
keyword.
由于该类实现了 IDispose
,因此您可以像这样使用 using
关键字:
Because the class implements IDispose
, you can use the using
keyword like this:
using ( TfsTeamProjectCollection x = New TfsTeamProjectCollection(...) ) {
... usage
}
这将关闭连接.回到第一点,c#不会像
This will close the connection. To go back to the first point, c# does not implement deterministic destructors like C++. Instead the object is garbage collected at some point in the future, which you have limited/no control of.
因为该对象具有 finalizer 该连接它保持打开状态,当垃圾收集器运行时将被调用.但是,在连接用尽之前,GC尚未运行.
Because the object has a finalizer the connection it is holding open, will be called when the garbage collector runs. However, the GC is not running before you're running out of connections.
这篇关于服务用尽TCP连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!