Windows 서비스에서 타이머를 사용하려고합니다. 이 서비스는 시작 및 중지 할 수 있으며 이런 일이 발생하면 이벤트 로그에 내용을 기록합니다. 내 문제는 또한 timeElapsed 이벤트가 발생할 때마다 계속 실행되고 이벤트 로그에 이벤트를 기록하는 타이머를 사용하려고한다는 것입니다. 편집장기 실행 Windows 서비스에서 타이머 사용
:는 (I 코드를 변경, 그래서 타이머 아직도 내가, 이벤트 로그에 로그 항목이 기대하는 결과가 아니다 필드이지만)
using System.Timers;
서비스를 초기화하지 : 시작 이벤트에
public Timer timer;
public MonitorService()
{
InitializeComponent();
timer = new Timer(10000);
//Some code that really doesn't matter
}
protected override void OnStart(string[] args)
{
// Hook up the Elapsed event for the timer.
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Enabled = true;
timer.Start();
EventLogger.WriteEntry("Biztalk monitoring service started", EventLogEntryType.SuccessAudit);
// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
// GC.KeepAlive(timer);
}
private int count =0;
은 시간 제한 이벤트에 : 는
// Specify what you want to happen when the Elapsed event is
// raised.
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
//Some other code that doesn't mather
count++;
EventLogger.WriteEntry(string.Format("TimerEvent has ran {0} times. Total time is: {1}", count, e.SignalTime), EventLogEntryType.Information);
}
온을 (이 이벤트에 기록하는 항목 내가 할 것으로 예상하면서, 매 10 초마다 로그 파일이 없습니다 작동하지 않을 것입니다) 정지 이벤트 :
protected override void OnStop()
{
EventLogger.WriteEntry("Biztalk monitoring service stopped", EventLogEntryType.Warning);
}
홈페이지
이미 ///<summary>
///The main entry point for the application.
///</summary>
static void Main()
{
var servicesToRun = new ServiceBase[]
{
new MonitorService()
};
ServiceBase.Run(servicesToRun);
}
를 묻는 :이 궁금해하는 사람들을 위해
는 Program.cs 내 주요 방법이다? 네 확실합니다!
나는이 질문에 앞서 여기에 같은 질문되었다는 사실을 알고 : Windows service with timer 및 Best Timer for using in a Windows service
하지만 그 솔루션은 내 문제를 해결하지 않는 것 같습니다.
모든 의견을 환영합니다!
나는 System.Timers.Timer를 사용하지 말 것을 강력히 권유한다. 왜냐하면 예외를 삼켜 버리고 버그를 숨기기 때문이다. Elapsed 이벤트에서 예외가 발생하면 결코 알 수 없습니다. http : // blog를 참조하십시오.mischel.com/2011/05/19/swallowing-exceptions-is-hiding-bugs/. 당신은 1) 이벤트 처리기를'try/catch '로 보호해야하고, 2)'System.Threading.Timer'를 사용해야합니다. –
@JimMischel 방금이 사실이 내 문제 였고 이제 귀하의 의견을 보았습니다. 그것은 단지 예외를 삼키고 있었고, 거기서는 효과가 없었습니다. System.Threading.Timer가이 모든 것을 수정합니까? –
'System.Threading.Timer'는 예외를 삼키지 않을 것이고, 이것은 당신의 핸들러에서 잘못된 것이 있음을 알려줄 것입니다. 실제 해결책은 타이머 이벤트 핸들러에서 예외를 처리하는 것에 매우주의해야합니다. –