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