2

I have a WCF service hosted in a Windows Service. The WCF service has a thread that makes a UdpClient connection to an outside system. I am finding that when the Windows Service is stopped that the thread is not always gracefully shutting down and calling the UdpClient.Close() method which is leaving that connection open (or socket I think). Then when I go to run it again it blocks and the UdpClient never receives broadcasted packets. I am thinking that my problem is that I am not ever calling UdpClient.Close when the Windows Service is stopped. So my question is how would I release those resources properly? Here is the code for my Windows Service.

public class MyWindowsService : ServiceBase
{
    public ServiceHost serviceHost = null;

    public MyWindowsService()
    {
        ServiceName = "MyWindowsService";
    }

    public static void Main()
    {
        ServiceBase.Run(new MyWindowsService());
    }

    protected override void OnStart(string[] args)
    {
        if(serviceHost != null)
        {serviceHost.Close();}

        serviceHost = new ServiceHost(typeof(MyWCFService));
        serviceHost.Open();
    }

    protected override void OnStop()
    {
        if(serviceHost != null)
        {
            //Need to release unmanaged resources in the
            //WCF service here. How would I reference my
            //WCF service and send it a message to stop the threads?

            serviceHost.Close();
            serviceHost = null;
        }
    }
}
Corey Burnett
  • 7,312
  • 10
  • 56
  • 93
  • Take a look at the WCF service's OnClose event and stop the thread there. – Tim Jan 30 '13 at 15:25
  • I'm not sure what that means. There is no OnClose event for a WCF service that I am aware of. – Corey Burnett Jan 30 '13 at 15:29
  • Correct (I was thinking ServiceHost), but the principal remains the same. Find a handler that is called when a program (or maybe the AppDomain) is terminating, and kill the thread there. Not sure what the appropriate handler would be, and it may vary depending on what kind of WCF service you're running. – Tim Jan 30 '13 at 16:31

2 Answers2

0

Implement IDisposable in your WCF Service class, and clean up resources in the Dispose method.

WCF will call Dispose on each instance of the service when its lifetime has finished (i.e. end of call, or end of session, according to the instancing mode). Or, if you are using a singleton instance, you control the lifetime, so you can call Dispose at the proper time

Chris Dickson
  • 11,964
  • 1
  • 39
  • 60
0

Implement IDisposable in your MyWCFService, on dispose cleanup all used resources. http://msdn.microsoft.com/en-us/library/system.idisposable.aspx states:

The primary use of this interface is to release unmanaged resources.

Luuk
  • 1,959
  • 1
  • 21
  • 43