惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
F
Fortinet All Blogs
Cloudbric
Cloudbric
P
Palo Alto Networks Blog
T
Threatpost
T
Tor Project blog
T
Tenable Blog
AWS News Blog
AWS News Blog
Project Zero
Project Zero
L
LangChain Blog
Cyberwarzone
Cyberwarzone
Engineering at Meta
Engineering at Meta
雷峰网
雷峰网
C
CERT Recently Published Vulnerability Notes
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Latest
Security Latest
云风的 BLOG
云风的 BLOG
I
Intezer
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Proofpoint News Feed
A
Arctic Wolf
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Google DeepMind News
Google DeepMind News
V
Vulnerabilities – Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
MongoDB | Blog
MongoDB | Blog
aimingoo的专栏
aimingoo的专栏
K
Kaspersky official blog
Jina AI
Jina AI
N
News | PayPal Newsroom
T
The Blog of Author Tim Ferriss
D
DataBreaches.Net
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Secure Thoughts
TaoSecurity Blog
TaoSecurity Blog
P
Privacy & Cybersecurity Law Blog
P
Proofpoint News Feed
MyScale Blog
MyScale Blog
IT之家
IT之家
Forbes - Security
Forbes - Security
The Hacker News
The Hacker News
Last Week in AI
Last Week in AI
T
Threat Research - Cisco Blogs
Y
Y Combinator Blog

博客园 - Lance Yang

批量插入Oracle,遇到CLob字段慢的解决办法 c#,利用WPF的ScaleTransform和TranslateTransform实现图片的缩放效果 自定义控件如何给特殊类型的属性添加默认值 z(转) Oracle 12c心得 Entity Framework Code First (八)迁移 Migrations EF Code First学习笔记 全方位掌握 NSIS 的操作 NSIS学习笔记(转) C#开源框架(整理) 十大前端开发框架(转) .Net 学习 C# 实现无焦点窗体(转载) C++C#时间转换 C#调用C++导出类(转) Socket异步发送的同步控制 自己编码实现数据库的映射实体的代码生成器 C# P/Invoke中传递数组参数 Digital image processing In C# C#数字图像处理(摘录)
C#判断程序是由Windows服务启动还是用户启动
Lance Yang · 2016-06-05 · via 博客园 - Lance Yang

      在Windows系统做网络开发,很多时候都是使用Windows服务的模式,但在调度阶段,我们更多的是使用控制台的模式。在开发程序的时候,我们在Program的Main入口进行判断。最初开始使用Environment.UserInteractive属性,在系统不系统服务的交互模式时,程序运行是正常的,但试过有Win7下,系统允许交互模式,结果在服务启动的时候,跳转到控制台的模式了,服务启动不起来。只能在服务的调用方式下带参数,然后在Main的参数中判断是否为服务方式。这在一般的情况下是可以解决问题的。

      后来有好几个项目,使用了开源的Socket框架,框架本身是通过配置来启动服务的,这样,就没有经过用户的Main方法了,启动带参数的方法不行了,如果为了判断启动模式而加单独的配置,不是很好的做法,通过Program加全局标识是可以解决程序自身启动同框架启动的判断,但服务如果是通过自身的Main启动,又只能靠加参数的方法了,整个实现感觉都是有点别扭。

      在几次的服务程序开发中,遇到一个写文件的路径问题,即取路径总是不对,通过分析,Windows服务启动时的环境默认路径是从System32目录,可能是Windows服务的宿主程序是从这开始的吧,这就有了解决如何判断启动模式的方法了。主要是通过宿主程序是程序集所在的目录来判断。具体如下 :

  string curPath = System.Environment.CurrentDirectory;
  string basePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
  bool isRunWinService = (curPath != basePath);

如果两个路径不相同,我就认为是启动Windows服务了。我们只要在程序的开始做判断,这样Environment.CurrentDirectory的路径还是宿主程序,一般来说,开发人员很少去改动Environment.CurrentDirectory的。这样我们做好的Exe程序支持用户启动,服务启动,或框架自动的服务管理等模式了。