"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)" 完成订单结算后,就不能再做任何处理。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
[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),
host.AddServiceEndpoint(
typeof
(IOrderService),
new
WSHttpBinding(),
""
);
host.Open();
});
//-----------------------
IOrderService order = ChannelFactory<IOrderService>.CreateChannel(
new
WSHttpBinding(),
using
(order
as
IDisposable)
{
order.Init();
order.DoSomething();
order.Process();
}
}
}
|
如何客户端不按照这个次序调用,则会触发异常。
错误1
1
2
3
4
5
6
7
8
|
IOrderService order = ChannelFactory<IOrderService>.CreateChannel(
new
WSHttpBinding(),
using
(order
as
IDisposable)
{
//order.Init();
order.DoSomething();
order.Process();
}
|
异常
未处理 System.InvalidOperationException
1
|
Message=
"The operation 'DoSomething' cannot be the first operation to be called because IsInitiating is false."
|
错误2
1
2
3
4
5
6
7
8
9
|
IOrderService order = ChannelFactory<IOrderService>.CreateChannel(
new
WSHttpBinding(),
using
(order
as
IDisposable)
{
order.Init();
order.DoSomething();
order.Process();
order.DoSomething();
}
|
异常
未处理 System.InvalidOperationException
1
|
Message=
"This channel cannot send any more messages because IsTerminating operation 'Process' has already been called."
|