我正在C#,Visual Studio 2010 IDE中實現Windows服務。在C#中實現的Windows服務無法在任務管理器/服務中啓動
我首先嚐試使用定時器每5秒寫入一個文件的小應用程序,並且完美地工作。良好的服務和一切開始。
經過這個測試後,我需要做的是寫一個文件「進入USB存儲器」和「移除USB存儲器」的服務。我記錄了我進入記憶的次數。
這是我的代碼。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;
using System.Management;
using System.Threading.Tasks;
using System.Threading;
namespace Test
{
public partial class Service1 : ServiceBase
{
System.Timers.Timer tim = null;
public Service1()
{
InitializeComponent();
backgroundWorker1.RunWorkerAsync();
/* tim = new System.Timers.Timer();
tim.Interval = 5000;
tim.Elapsed += new ElapsedEventHandler(tim_Elapsed); */
}
/*void tim_Elapsed(object sender, ElapsedEventArgs e)
{
TextWriter text = new StreamWriter(@"C:\log.txt", true);
text.WriteLine(DateTime.Now.ToString());
text.Close();
} */
private void WriteFile(string que)
{
TextWriter text = new StreamWriter(@"C:\log.txt", true);
text.WriteLine(que);
text.Close();
}
protected override void OnStart(string[] args)
{
tim.Start();
}
protected override void OnStop()
{
tim.Stop();
}
private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
Console.WriteLine(property.Name + " = " + property.Value);
}
WriteFile("USB memory is entered");
}
void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
Console.WriteLine(property.Name + " = " + property.Value);
}
WriteFile("remove USB memory");
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery);
insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
insertWatcher.Start();
WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery);
removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
removeWatcher.Start();
System.Threading.Thread.Sleep(20000000);
}
}
}
事實是,當服務達到任務管理器/服務,總是停止,DOI你右擊並開始,並且保持停止。
如果計時器工作正常,我只是開始,因爲這段代碼不? 我可以有這個問題嗎? ?任何想法認爲
如果您右鍵單擊它,並且它在啓動時未啓動,則可能是未處理的異常。轉到事件日誌並檢查應用程序中的日誌,如果發生未處理的異常,該日誌會自動創建。 –