欢迎访问 生活随笔!

尊龙游戏旗舰厅官网

当前位置: 尊龙游戏旗舰厅官网 > 编程语言 > c# >内容正文

c#

c#实现windows后台服务实例浅析 -尊龙游戏旗舰厅官网

发布时间:2025/1/21 c# 26 豆豆
尊龙游戏旗舰厅官网 收集整理的这篇文章主要介绍了 c#实现windows后台服务实例浅析 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

2019独角兽企业重金招聘python工程师标准>>>

c#实现windows后台服务实例之前要明白的一些概念:所谓windows后台服务,即后台自动运行的程序,一般随操作系统启动而启动,在我的电脑 服务后应用程序 服务里面能看到当前电脑的服务.一般而言,程序上用vc、c 写windows服务,但是我对这些语言不是很熟,一般编程用c#较多,所以就用c#语言写了一个windows服务.

c#实现windows后台服务实例其实需求是这样的,做那个报价系统的时候加入了发短信的功能,订单处理完即将发货的时候要发送短信都客户手机上,公司内部员工处理订单超时要自动发短信,群发产品促销信息到客户手机上等,还有定时发送短信的需求,所以最后面决定把发短信的模块独立出来,以后还有什么功能方便一起调用,而最终选择了采用windows后台服务.

c#实现windows后台服务实例其实windows服务并不好做到通用,它并不能在用户的界面显示一些什么信息等,它只是在后台默默的处理一些事情,起着辅助的作用.那如何实现发送段信通用调用的接口呢?它们之间的信息又是如何来交互呢?数据库!对,就是它存储数据信息的.而数据库都能很方便的访问操作.把发送短信的后台服务定时去访问一个数据库,而另外任何要发送短信的地方也访问数据库,并插入一条要发送的短信到表里面,稍后windows后台服务访问该表将此短信发送出去.这可能是一个比较蠢的方法,但实现起来较简单.

c#实现windows后台服务实例首先,由于它是要安装的,所以它运行的时候就需要一个安装类installer将服务安装到计算机,新建一个后台服务安装类继承自installer,安装初始化的时候是以容器进行安装的,所以还要建立serviceprocessinstaller和serviceinstaller服务信息组件添加到容器安装,在installer类增加如下代码:

private system.componentmodel.icontainer components = null;  private system.serviceprocess.serviceprocessinstaller spinstaller;  private system.serviceprocess.serviceinstaller sinstaller;  private void initializecomponent()  {  components = new system.componentmodel.container();   // 创建serviceprocessinstaller对象和serviceinstaller对象  this.spinstaller = new system.serviceprocess.serviceprocessinstaller();  this.sinstaller = new system.serviceprocess.serviceinstaller();   // 设定serviceprocessinstaller对象的帐号、用户名和密码等信息  this.spinstaller.account = system.serviceprocess.serviceaccount.localsystem;  this.spinstaller.username = null;  this.spinstaller.password = null;   // 设定服务名称  this.sinstaller.servicename = "sendmessage";  sinstaller.displayname = "发送短信服务";  sinstaller.description = "一个定时发送短信的服务";   // 设定服务的启动方式  this.sinstaller.starttype = system.serviceprocess.servicestartmode.automatic;   this.installers.addrange(new system.configuration.install.installer[] { this.spinstaller, this.sinstaller });  } c#实现windows后台服务实例再添加一个服务类继承自servicebase,我们可以重写基类的onstart、onpause、onstop、oncontinue等方法来实现我们需要的功能并设置指定一些属性.由于是定事发送短信的服务,自然少不了windows记时器,在onstart事件里我们写入服务日志,并初始化记时器.

private system.timers.timer time;  private static readonly string currentpath = application.startuppath "\\";  protected override void onstart(string[] args)  {  string path = currentpath "log\\start-stop.log";  filestream fs = new filestream(path, filemode.append, fileaccess.write);  streamwriter sw = new streamwriter(fs);  sw.writeline("the service is starting on " datetime.now.tostring());  sw.flush();  sw.close();  fs.close();   time = new system.timers.timer(1000 * convert.toint32(getsettings("timespan")));  time.enabled = true;  time.elapsed = this.timeout;  time.start();  } c#实现windows后台服务实例实例化记时器类启动后,将在指定时间间隔触发elapsed指定事件,如上getsettings为读取我app.config文件里一个配置节点(值为30)的方法,所以上面将会每隔30秒调用timeout方法.而改方法就是我们发短信的具体操作.代码如下:

private void timeout(object sender, eventargs e)  {  try {  if (getsettings("enabled").tolower() == "true")  {  sqlconnection con = new sqlconnection(getsettings("connstring"));  sqlcommand cmd = new sqlcommand("select [sysid],[admin_inner_code],[user_inner_code],[phone],[message],[sendtime] from [tbl_note_outbox]", con);  con.open();  sqldatareader rdr = cmd.executereader();  while (rdr.read())  {  string phone = rdr["phone"].tostring();  string message = rdr["message"].tostring();  string sendtime = rdr["sendtime"].tostring();  system.text.encoding encoder = system.text.encoding.getencoding("gb2312");  string url = string.format("http://211.155.23.205/isapi.dll?sendsms&agentid={0}&password={1}&phone={2}&msg={3}&sendtime={4}", getsettings("agentid"), getsettings("password"), phone,system.web.httputility.urlencode( message,encoder), sendtime);  system.net.webclient wclient = new system.net.webclient();  string msg = system.text.encoding.default.getstring(wclient.downloaddata(url));  wclient.dispose();   //删除已经发送成功的,并保存发送记录  if (msg == "发送成功")  {  datetime dtsend = sendtime == "0" ? datetime.now : datetime.parseexact(sendtime, "yyyymmddhhmmss", null);  string sql = string.format("delete from [tbl_note_outbox] where [sysid]={0} insert into [tbl_note_log] ([admin_inner_code],[user_inner_code],[status],[phone],[message],[sendtime]) values('{1}','{2}','{3}','{4}','{5}','{6}')", rdr["sysid"], rdr["admin_inner_code"], rdr["user_inner_code"], msg, phone, message, dtsend);  sqlconnection conn = new sqlconnection(getsettings("connstring"));  sqlcommand delete = new sqlcommand(sql, conn);  conn.open();  delete.executenonquery();  conn.close();  delete.dispose();  }   }  rdr.close();  con.close();  cmd.dispose();  }  }  catch (exception ex)  {  string errorpath = currentpath "log\\error.log";  if (!file.exists(errorpath))  {  filestream create = file.create(errorpath);  create.close();  }  filestream fs = new filestream(errorpath, filemode.append, fileaccess.write);  streamwriter sw = new streamwriter(fs);  sw.writeline("exception: " ex.message " --" datetime.now.tostring());  sw.flush();  sw.close();  fs.close();  }   } c#实现windows后台服务实例上面我们使用try、catch访问数据库,并记录错误异常信息. 发送短信是使用发送一个web请求发送出去的,要注意请求url字符串的编码类型,要与请求页面编码一致,不然会出现乱码.上面我们请求的是智网通集团短信(网址:http://www.09168.net/)的web接口,通过访问他的网站来实现发短信,当然还要传递一些用户名、密码、手机号码和要发送的短信息等参数.他的收费平均大概为7分/条的样子,其实我原本不想用发送web请求的这样方式来发送短信的,它本身提供了调用它发送短信的dll,而且还有vc、delphi调用的demo,但是没有用c#调用的例子,我刚开始试着用非托管动态链接库他提供的dll,不知方法调用那里出错了一直都没能成功发送出短信,所以后来就用了他的web方式接口了.他页面直接返回发送短信的状态信息.返回发送成功则短信发送成功,成功后我再将此条信息从要发送短信表里删除并保存在发送记录表里面,以备日后方便查询.其实登陆他的尊龙游戏旗舰厅官网进入后台也能方便的查询,如下图.

 

c#实现windows后台服务实例发送短信服务的代码基本上搞定了,就看怎么在服务器上安装部署了.c#写的windows后台服务不能直接安装,需要借助.net framework里面的installutil.exe安装工具安装,我们可以做成一个执行cmd命令的文件bat文件来安装启动它,命令如下:

%windir%\microsoft.net\  framework\v2.0.50727\  installutil.exe �%\  sendmessage.exe  net start sendmessage 

安装完成以后,我们可以在我的电脑管理服务里面看到才安装上的后台服务.

 

经测试,采用定时访问数据库发送短信的服务并不是很耗资源,刚启动的时候只占用内存为7、8m左右,经过在服务器上连续运行几天不关闭占用的内存也只升到15m左右,运行比较稳定,这里提供一个短信二次开发接口说明,有兴趣的朋友可以去下载看下.

智网动力集团短信二次开发说明文档示例

特别申明:本文及内容如非特别注明,均为本人jonllen原创,尊龙游戏旗舰厅官网的版权均归原作者个人所有,转载必须保留此段声明源码天空,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

c#实现windows后台服务实例的基本情况就向你介绍到这里,希望对你了解和学习c#实现windows后台服务实例有所帮助。

详细请参考:http://www.codesky.net/article/200908/128303.html

转载于:https://my.oschina.net/u/582827/blog/228621

总结

以上是尊龙游戏旗舰厅官网为你收集整理的c#实现windows后台服务实例浅析的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得尊龙游戏旗舰厅官网网站内容还不错,欢迎将尊龙游戏旗舰厅官网推荐给好友。

网站地图