Windows服務 樣本簡要說明(系統事件日誌、運行批處理、安裝卸載、啟動調試)

來源:互聯網
上載者:User

一般來說,使用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)一樣

這樣就可以調試了,接下來就可以做各種各樣的編碼工作了!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.