如何在构建WCF Service类之后调用方法?

时间:2013-09-12 15:33:02

标签: c# .net wcf

我想在调用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
     }     

}

1 个答案:

答案 0 :(得分: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;
        }
    }     
}