您的位置:首页 > 其它

Windows服务 示例简要说明(系统事件日志、运行批处理、安装卸载、启动调试)

2011-07-14 14:47 916 查看
一般来说,使用Windows服务多半是用于监控,应用范围包含了硬件控制、应用程序监视、系统级应用、诊断、报告、Web和文件系统服务等功能,用处十分广泛。

这里简要说明一下windows服务的基本使用,即代码编写、调试方法、安装与卸载。

新建Windows服务项目后,在Service中可以看到重载了启动、停止方法,当然还有暂停和继续……

protected override void OnStart(string[] args)
{
Thread.Sleep(1000 * 10);
mainThread.Start();
}

protected override void OnStop()
{
mainThread.Abort();
}

顺便提一下,在服务代码中一般都会用写文件、线程、通过注册表读写用户信息等操作,所以这些应用也是很重用的。

StreamWriter sw = null;
if (!File.Exists(filePath))
{
sw = File.CreateText(filePath);
}
else
{
sw = File.AppendText(filePath);
}

if (sw != null)
{
sw.WriteLine("-------------------------监测日志---------------------");
sw.WriteLine(currentDateTime.ToString());
sw.WriteLine(applicationLog);
sw.Close();
}

Windows Log

string[] logs = new string[] { "Application"/*, "System" */};
StringBuilder result = new StringBuilder();
foreach (string log in logs)
{
EventLog eventLog = new EventLog();
eventLog.Log = log;
//eventLog.Source = "Application Error";
foreach (EventLogEntry entry in eventLog.Entries)
{
if (entry.TimeGenerated >= queryTime || entry.TimeWritten >= queryTime)
{
if (entry.EntryType == EventLogEntryType.Error && entry.Source == "Application Error")
{
result.Append(log);
result.Append(entry.EntryType.ToString());
result.Append("(" + entry.TimeWritten.ToString() + "):");
result.Append(entry.Message);

isRestartAmpJettyService = true;
}
}
}
}

operation regedit,Execute bat file,kill process

string keyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";
RegistryKey currentUser = Registry.CurrentUser;
RegistryKey shellKey= currentUser.OpenSubKey(keyPath);

if (softwareKeys != null)
{
desktopValue = shellKey.GetValue("Desktop").ToString();
result = true;
}

Process process = new Process();
process.StartInfo.FileName = desktopPath + "ServerJetty.bat";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();

WriteLog(process.StandardOutput.ReadToEnd());

Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
if (process.ProcessName.ToLower().CompareTo("java") == 0)
{
process.Kill();
}
}

  

编写安装和卸载服务

进入Service的设计界面,右击选择“add installer”就会添加相应的服务,如下



为其serviceInstaller和serviceProcessInstaller分别设置名称,描述信息,应用账户(一般用LocalSystem、LocalService、NetworkService、User),启动类型(自动、手动、禁用)。

完成以上操作后,基本上就可以了,现在只需安装此服务即可,项目是不能通过F5直接Run或Debug的,需要Attach Process才可以进行调试,在调试前需要安装服务。

安装卸载服务的命令,需要使用.NetFramework中的InstallUtil.exe(win vista/7/需要注意执行这个命令时设置兼容性以"管理员身价运行")

InstallUtil.exe在目录C:\Windows\Microsoft.NET\Framework\v4.0.30319,根据版本号确定具体目录,



安装服务结果,



服务调试,直接F5



这样是不行的,需要附加到进程,附加到近程就需要对其服务启动后才能加载进程,否则是找不着这个进程的。


,直接(Ctrl+Alt-P)一样



这样就可以调试了,接下来就可以做各种各样的编码工作了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐