0

我想在调用 WCFService() 构造函数后调用方法“ StartListen() ”,我可以在第一次客户端调用后调用此方法“StartListen()”,但不管客户端调用如何,我想在服务之后执行此操作类是构造的,有可能吗?或者是否有任何其他机制可以满足这种需求?

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 
public class WCFService : IWCFService
{
    public WCFService()
    {
        // do initializing here
    }

     // implementation of the operation contract 
     public void NotifyToService()
     {
        // method will be called by the client
     }   

    //this internal method has to be called after the class is constructed
    public void StartListen()
     {
        // some listening action
     }     

}
4

1 回答 1

0

由于您使用InstanceContextMode.Single的是“最简单”的方法,因此它是一个私有标志,您检查循环是否已启动,如果没有启动则启动它。

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 
public class WCFService : IWCFService
{
    public WCFService()
    {
        // do initializing here
    }

     // implementation of the operation contract 
     public void NotifyToService()
     {
        CheckForStartListen();
        // method will be called by the client
     }   

    //this internal method has to be called after the class is constructed
    public void StartListen()
    {
        // some listening action

    } 

     private readonly Object _initizeLockObject = new Object();
     private bool _initialized = false;


    private void CheckForStartListen()
    {
        if(_initialized)
            return;

        lock(_initizeLockObject)
        {
            if(_initialized) //Double checked locking to see if it was initialized while we wait
                return;

            StartListen();
            _initialized = true;
        }
    }     
}
于 2013-09-12T16:27:42.790 回答