简体   繁体   中英

Can an WCF Service create his own host?

I have a client / server type of application and I'd like the server object to create his own host. It looks something like this:

public class Server : IServer {
  private ServiceHost m_Host;
  public Server() {
    m_Host = new ServiceHost(this);
    m_Host.Open();
  }
}

It seems to work fine when there are few message transfers occurring. But when it starts to speed up (my application requires that data is transfered every 50 ms), the server hangs and and the transfers stop after a few seconds without throwing an exception.

So, is it possible for an object to create his own host? Or do I really have to create it in the main() or do something else?

EDIT: I think the problem in this case is that I want the object that implements the service itself to create his own ServiceHost.

There's nothing really stopping any object to create an instance of ServiceHost.

The big question then is - can you guarantee that your object containing the service host is "alive"? Or was it garbage collected by any chance?

We use Windows (NT) Services to host our own custom service host classes to provide around-the-clock availability for WCF services - works just fine.

Marc

To be a WCF service it simply needs to implement the service contract. There's nothing to stop you adding more methods to open and close an instance of itself as a service.

Check out the ServiceBehaviorAttribute which allows you to specify how your service ... behaves. ;) The ConcurrencyMode property defined the support for multithreading and defaults to single threaded mode, and the InstanceContextMode defines if the service object is per session, per call or singleton.

Quote from ConcurrencyMode:

Setting ConcurrencyMode to Single instructs the system to restrict instances of the service to one thread of execution at a time, which frees you from dealing with threading issues. A value of Multiple means that service objects can be executed by multiple threads at any one time. In this case, you must ensure thread safety.

Quote from InstanceContextMode:

If the InstanceContextMode value is set to Single the result is that your service can only process one message at a time unless you also set the ConcurrencyMode value to Multiple.

We could really use some code examples of your service to further debug the behavior you're describing. For example, is your service object expensive to construct (assuming non singleton implementation), or do the operation slow down? Do you know where the time is spent, is it code, or could it as well be some firewall that limits connection? What protocol do you use?

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