示例代码下载地址:WCFDemo1Day

概述

客户端向WCF服务发出请求后,服务端会实例化一个Service对象(实现了契约接口的对象)用来处理请求,实例化Service对象以及维护其生命周期的方式在WCF中共有三种不同的类型,分别是:

  • Per-Call
  • Per-Session
  • Single

程序中通过设置ServiceBehavior特性来指定,如下:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class CommService : ICommContract
{
}

这是枚举InstanceContextMode的内容:

public enum InstanceContextMode
{
PerSession = 0,
PerCall = 1,
Single = 2,
}

Per-Call

每次调用服务端服务端方法,服务端都会实例化一个对象来处理请求,为观察结果,现编写如下代码:

服务类:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class CommService : ICommContract
{
public CommService()
{
Console.WriteLine("构造函数被执行");
} public int Add(int a, int b)
{
Console.WriteLine("Add被调用,Thread:" + Thread.CurrentThread.ManagedThreadId + " fromPool:" + Thread.CurrentThread.IsThreadPoolThread); return a + b;
} public void Dispose()
{
Console.WriteLine("对象销毁");
Console.WriteLine("_____________________________");
} public void SendStr(string str)
{
Console.WriteLine("SendStr被调用,Thread:" + Thread.CurrentThread.ManagedThreadId + " fromPool:" + Thread.CurrentThread.IsThreadPoolThread);
}
}

如果服务类实现了接口IDisposable,当服务类被销毁时会回调Dispose方法,可以在Dispose方法中写一些WriteLine语句以观察对象的生命周期。

客户端代码:

class Program
{
static void Main(string[] args)
{
CommService.CommContractClient client = new CommService.CommContractClient(); client.SendStr("hello");
client.SendStr("hello");
client.SendStr("hello"); client.Close();
}
}

运行效果:

Per-Session

InstanceContextMode被设置为PerSession后,同一个客户端多次调用一个远程Web服务方法时,服务端只会实例化一次,修改上面的服务端代码第一行如下:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]

再看运行效果:

上面的实例代码所使用的绑定模式为WSHttpBinding,如果使用BasicHttpBinding的话,即使是指定了InstanceContextModePerSession服务端也不会保存会话,现将支持Per-Session的绑定方式列举如下:

  • WSXXXBinding(with Message security or reliability)
  • NetTcpXXXBinding
  • NetXXXPipeBinding

后两个容易理解,第一个括号里什么什么玩意儿,请看宿主代码:

 class Program
{
static void Main(string[] args)
{
Uri baseURI = new Uri("http://localhost:8000/Services");
ServiceHost host = new ServiceHost(typeof(CommService), baseURI); try
{
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.None;
host.AddServiceEndpoint(typeof(ICommContract), binding, "CommonService"); ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetUrl = new Uri("http://localhost:8080/Services");
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb); host.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine(); host.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
host.Abort();
}
}
}

binding.Security.Mode默认为Message,现在把它改成None再运行程序:

哈,虽然InstanceContextMode设置为了Per-Session,实际上还是Per-Call,这部分内容和安全性有关,希望我有时间以后会写到吧,今天暂时不去研究。

除了绑定方式,还有一个地方也影响到了Per-Session是否起作用,它是契约接口特性ServiceContract的属性SessionMode,该枚举内容如下:

public enum SessionMode
{
Allowed = 0,
Required = 1,
NotAllowed = 2,
}

SessionMode属性默认是Allowed,如果设置为Required表示必须启用会话模式,NotAllowed表示必须不能启动会话模式,Allowed表示无所谓。谁有兴趣可以一一尝试。现将契约接口的特性改成如下:

[ServiceContract(Namespace = "zzy0471.cnblogs.com.CommService", SessionMode = SessionMode.NotAllowed)]
public interface ICommContract : IDisposable
{
[OperationContract()]
int Add(int a, int b); [OperationContract()]
void SendStr(String str);
}

再运行程序:

虽然InstanceContextMode设置为了Per-Session,实际上还是Per-Call

此外,还有一个需要注意的地方,如果在方法契约特性中设置属性IsTerminatingtrue,如下图

[OperationContract(IsTerminating = true)]
void SendStr(String str);

运行服务端会导致运行时错误,IsTerminating设置为了truePer-Session模式相矛盾,IsTerminating的意思是:“获取或设置一个值,该值指示服务操作在发送答复消息(如果存在)后,是否会导致服务器关闭会话”

Per-Single

InstanceContextMode被设置为PerSingle后,所有的客户端请求都只有一个服务端实例对象来处理,服务启动时对象创建,服务关闭时对象销毁。现修改InstanceContextMode特性如下:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class CommService : ICommContract
{
public CommService()
{
Console.WriteLine("构造函数被执行");
} public int Add(int a, int b)
{
Console.WriteLine("Add被调用,Thread:" + Thread.CurrentThread.ManagedThreadId + " fromPool:" + Thread.CurrentThread.IsThreadPoolThread); return a + b;
} public void Dispose()
{
Console.WriteLine("对象销毁");
Console.WriteLine("_____________________________");
} public void SendStr(string str)
{
Console.WriteLine("SendStr被调用,Thread:" + Thread.CurrentThread.ManagedThreadId + " fromPool:" + Thread.CurrentThread.IsThreadPoolThread);
}
}

为了方便观察,修改客户端代码,以模拟多个客户端:

class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 3; i++)
{
CommService.CommContractClient client = new CommService.CommContractClient(); client.SendStr("hello");
client.SendStr("hello");
client.SendStr("hello"); client.Close();
}
}
}

运行程序:

Learning WCF:Life Cycle of Service instance的更多相关文章

  1. WCF技术剖析之二十三:服务实例(Service Instance)生命周期如何控制[下篇]

    原文:WCF技术剖析之二十三:服务实例(Service Instance)生命周期如何控制[下篇] 在[第2篇]中,我们深入剖析了单调(PerCall)模式下WCF对服务实例生命周期的控制,现在我们来 ...

  2. Learning WCF Chapter1 Creating a New Service from Scratch

    You’re about to be introduced to the WCF service. This lab isn’t your typical “Hello World”—it’s “He ...

  3. Learning WCF:Fault Handling

    There are two types of Execptions which can be throwed from the WCF service. They are Application ex ...

  4. Learning WCF:A Simple Demo

    This is a very simple demo which can help you create a wcf applition quickly. Create a Solution Open ...

  5. Learning WCF Chapter1 Hosting a Service in IIS

    How messages reach a service endpoint is a matter of protocols and hosting. IIS can host services ov ...

  6. Learning WCF Chapter1 Generating a Service and Client Proxy

    In the previous lab,you created a service and client from scratch without leveraging the tools avail ...

  7. Learning WCF Chapter1 Exposing Multiple Service Endpoints

    So far in this chapter,I have shown you different ways to create services,how to expose a service en ...

  8. WCF 的 Service Instance模式和并发处理

    WCF 的 Service Instance(实例)有三种模式 PerCall:每一次调用都创建一个实例,每一次调用结束后回收实例.此模式完全无状态. PerSession:调用者打开Channel时 ...

  9. WCF:为 SharePoint 2010 Business Connectivity Services 构建 WCF Web 服务(第 1 部分,共 4 部分)

    转:http://msdn.microsoft.com/zh-cn/library/gg318615.aspx 摘要:通过此系列文章(共四部分)了解如何在 Microsoft SharePoint F ...

随机推荐

  1. 对象转Json时,Date类型格式化问题

    object是一个对象,该对象中有一个字段为Date类型 使用JSONObject obj = JSONObject.fromObject(object);将Object转成json时 Date类型字 ...

  2. Android APK反编译(一)

    apk是安卓工程打包的最终形式,将apk安装到手机或者模拟器上就可以使用APP.反编译apk则是将该安卓工程的源码.资源文件等内容破解出来进行分析. 一.APK反编译基本原理 1.APK分析 apk文 ...

  3. windows系统下将nginx作为系统服务启动

    1. 准备工作 下载安装nginx,并记住安装目录 官网下载 下载winsw,下载地址 2. winsw设置 将winsw可执行程序复制到nginx安装目录下,并重命名为nginx-service 新 ...

  4. PostgreSQL使用笔记

    下载并安装 注意安装图形界面 pgAdmin 需要输入缺省用户 postgres 的密码 在 Windows 下安装之后注意把 bin文件夹加到 Path 环境变量中. 重置密码 使用管理员权限打开 ...

  5. 微信小程序页面跳转 的几种方式

    最近在做微信小程序,碰到页面跳转的问题,总结一下页面之间跳转的方式 一.wx.navigateTo(OBJECT) 这是最普遍的一种跳转方式,其官方解释为:“保留当前页面,跳转到应用内的某个页面” 类 ...

  6. 深度学习项目——基于卷积神经网络(CNN)的人脸在线识别系统

    基于卷积神经网络(CNN)的人脸在线识别系统 本设计研究人脸识别技术,基于卷积神经网络构建了一套人脸在线检测识别系统,系统将由以下几个部分构成: 制作人脸数据集.CNN神经网络模型训练.人脸检测.人脸 ...

  7. 配置MQTT服务器

    第一步:下载一个Xshell 链接:https://pan.baidu.com/s/16oDa5aPw3G6RIQSwaV8vqw 提取码:zsb4 打开Xshell 前往MQTT服务器软件下载地址: ...

  8. 用rekit创建react项目

    第一步  先进入github.com 然后搜索rekit 往下滑 1 . 先全局安装 npm install -g rekit 2 . 进入自己想要创建项目文件的目录输入 rekit create / ...

  9. 根据需要查找需要的第三方pyhton库

    1.可以在https://awesome-python.com/这个网站上按照分类去寻找,上面收录了比较全面的第三方库.比如我们想要找爬虫方面的库时,查看Web Crawling这个分类,就能看到相应 ...

  10. kubernetes namespace Terminating

    1.kubectl get namespace annoying-namespace-to-delete -o json > tmp.jsonthen edit tmp.json and rem ...