"IsInitiating=false" 表示执行该方法前,必须调用一个标注了 "IsInitiating=true" 的方法来创建 Session;而 "IsTerminating=true" 表示该方法调用结束后,WCF 将会释放服务对象,客户端代理将不能继续任何操作(除非我们创建一个新的代理)。IsInitiating 和 IsTerminating 只能用于启用了 Session 的服务对象上,缺省情况下 "IsInitiating=true, IsTerminating=false"。
我们可以使用 IsInitiating 和 IsTerminating 来控制服务对象的流程和状态,比如使用 "IsInitiating=false" 强制客户端在调用订单服务的任何操作前,必须使用 "Init(IsInitiating=true)" 来获取一个唯一流水号,而一旦调用 "Process(IsTerminating=true)" 完成订单结算后,就不能再做任何处理。
[ServiceContract(SessionMode = SessionMode.Required)]
public interface IOrderService
{
[OperationContract(IsInitiating = true)]
void Init();
[OperationContract(IsInitiating = false, IsTerminating = false)]
void DoSomething();
[OperationContract(IsInitiating = false, IsTerminating = true)]
void Process();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class OrderService : IOrderService
{
public void Init()
{
Console.WriteLine("Init...");
}
public void DoSomething()
{
Console.WriteLine("DoSomething...");
}
public void Process()
{
Console.WriteLine("Process...");
}
}
public class WcfTest
{
public static void Test()
{
AppDomain.CreateDomain("Server").DoCallBack(delegate
{
ServiceHost host = new ServiceHost(typeof(OrderService),
new Uri("http://localhost:8080/MyService"));
host.AddServiceEndpoint(typeof(IOrderService), new WSHttpBinding(), "");
host.Open();
});
//-----------------------
IOrderService order = ChannelFactory<IOrderService>.CreateChannel(new WSHttpBinding(),
new EndpointAddress("http://localhost:8080/MyService"));
using (order as IDisposable)
{
order.Init();
order.DoSomething();
order.Process();
}
}
}
如何客户端不按照这个次序调用,则会触发异常。
错误1
IOrderService order = ChannelFactory<IOrderService>.CreateChannel(new WSHttpBinding(),
new EndpointAddress("http://localhost:8080/MyService"));
using (order as IDisposable)
{
//order.Init();
order.DoSomething();
order.Process();
}
异常
未处理 System.InvalidOperationException
Message="The operation 'DoSomething' cannot be the first operation to be called because IsInitiating is false."
错误2
IOrderService order = ChannelFactory<IOrderService>.CreateChannel(new WSHttpBinding(),
new EndpointAddress("http://localhost:8080/MyService"));
using (order as IDisposable)
{
order.Init();
order.DoSomething();
order.Process();
order.DoSomething();
}
异常
未处理 System.InvalidOperationException
Message="This channel cannot send any more messages because IsTerminating operation 'Process' has already been called."
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zengjibing/archive/2009/01/17/3813174.aspx