简体   繁体   中英

Service running out of TCP connections

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);  

}

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);

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.

So my question is two-fold:

  1. In a windows service, if I instantiate a new class, it gets destroyed as soon as the method ends, right?
  2. 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?

Overall, what should I do for the service itself when using FileMonitor - should I be destroying it manually, or let garbage collection destroy it?

  1. No it doesn't
  2. Either call Disconnect , or better still use the using keyword.

Because the class implements IDispose , you can use the using keyword like this:

using ( TfsTeamProjectCollection x = New TfsTeamProjectCollection(...) ) {
    ... usage
}

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.

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.

The TfsTeamProjectCollection object implements IDisposable because it uses unmanaged resources. As with any other object that implements the IDisposable interface you should call the dispose method when you've finished using it. If you don't then it can hold on to resources.

The easiest way to do this is to wrap it in a using statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM