简体   繁体   中英

WCF Service Still Callable When Windows Service Has Been Stopped

I have written a windows service in C# .NET. This windows service contains a WCF service. I then use a new ServiceHost in the OnStart of the windows service to listen for messages for the WCF service. And close this ServiceHost in the OnStop.

When the service is running I can call the WCF service just fine. However, I then stop the service but can still call the WCF service. I wasn't expecting this to happen. What is going on?

OnStart and OnStop code is below

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

        serviceHost = new ServiceHost(typeof(MyService));

        // Open the ServiceHostBase to create listeners and start 
        // listening for messages.
        serviceHost.Open();
    }

    protected override void OnStop()
    {
        if (serviceHost != null)
        {
            serviceHost.Close();
            serviceHost = null;
        }
    }

Does your OnStop method look something like this:

protected override void OnStop()
{
  if (serviceHost != null)
  {
      try {
          serviceHost.Close();
      }catch{
          //could throw an exception if it is in a bad state
      }finally{
          serviceHost = null;
      }
  }
}

Second thing to check is that your OnStop is being called, it will not call stop if CanStop flag is false.

I have now solved this and thought I would update with the answer. Although I doubt anyone else would be so stupid;)

I had added the reference to my client app by right clicking on the project and selecting "Add Reference" rather than "Add Service Reference". I am still not sure why this allows the service to be called when it is not running but now I have added it as a Service Reference everything works as expected.

Thanks for everyone's input.

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