2017-03-02 71 views
0

我已經嘗試遵循MSDN簡單的做一個服務的指導不能使MSDNs簡單的例子,C#服務

演練:在組件設計器創建一個Windows服務應用程序 https://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Diagnostics; 
using System.Linq; 
using System.ServiceProcess; 
using System.Text; 

namespace WindowsService1 
{ 
    public partial class Service1 : ServiceBase 
    { 

     private System.ComponentModel.IContainer components; 
     private System.Diagnostics.EventLog eventLog1; 

     public Service1() 
     { 
      InitializeComponent(); 
      eventLog1 = new System.Diagnostics.EventLog(); 
      if (!System.Diagnostics.EventLog.SourceExists("MySource")) 
      { 
       System.Diagnostics.EventLog.CreateEventSource("MySource", "MyNewLog"); 
      } 
      eventLog1.Source = "MySource"; 
      eventLog1.Log = "MyNewLog"; 
     } 

     protected override void OnStart(string[] args) 
     { 
      eventLog1.WriteEntry("In OnStart"); 
     } 

     protected override void OnStop() 
     { 
     } 


    } 
} 

我似乎在第二個障礙失敗,「添加功能的服務」

當我編譯我得到'WindowsService1.Service1.eventLog1'和'WindowsService1.Service1.Service1.eventLog1'之間的歧義和典型e'WindowsService1.Service1'已經包含了'組件'的定義

+0

您是否已經在設計器文件中定義了'components'和'eventLog1'? – DavidG

+0

似乎你不得不把變量稱爲eventLog1 –

+0

它會出現,但我沒有把它們放在那裏。在我明白構造函數是什麼之前,我只是盲目地遵循這些步驟。似乎只要將eventlog添加到設計視圖中,它就會爲組件和eventlog1創建兩個條目,但這些步驟並未提及刪除或編輯這些條目。 – user3520245

回答

0

感謝評論人們讓我在正確的位置尋找,似乎你不需要做第4步,它會在添加事件日誌時自動完成在設計視圖中。

Service1.designer.cs looks like this 

namespace WindowsService4 
{ 
    partial class Service1 
    { 
     /// <summary> 
     /// Required designer variable. 
     /// </summary> 
     private System.ComponentModel.IContainer components; 

     /// <summary> 
     /// Clean up any resources being used. 
     /// </summary> 
     /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> 
     protected override void Dispose(bool disposing) 
     { 
      if (disposing && (components != null)) 
      { 
       components.Dispose(); 
      } 
      base.Dispose(disposing); 
     } 

     #region Component Designer generated code 

     /// <summary> 
     /// Required method for Designer support - do not modify 
     /// the contents of this method with the code editor. 
     /// </summary> 
     private void InitializeComponent() 
     { 
      this.eventLog1 = new System.Diagnostics.EventLog(); 
      ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit(); 
      // 
      // Service1 
      // 
      this.ServiceName = "Service1"; 
      ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit(); 

     } 

     #endregion 

     private System.Diagnostics.EventLog eventLog1; 
    } 
}