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