표준 System.Timers.Timer 동작에 문제가 있습니다. 타이머는 일정 간격으로 Elapsed 이벤트를 발생시킵니다. 그러나 Elapsed 이벤트 핸들러 내에서 실행 시간이 타이머 간격을 초과하면 스레드 풀이 이벤트 처리 대기열에 들어가기 시작합니다. 이건 내 문제 야. 이는 Elapsed 이벤트 핸들러를 사용하여 데이터베이스에서 데이터를 가져 와서 데이터를 가져 와서 결과를 다시 데이터베이스에 저장하기 때문입니다. 그러나 데이터 처리는 한 번만 제공되어야합니다. 그래서, System.Timers.Timer에 대한 경과 이벤트를 큐에 저장하지 못하게하는 방법이 있습니까?System.Timers.Timer가 스레드 풀에서 실행 대기열에 들어가는 것을 방지하려면 어떻게해야합니까?
public class EntryPoint
{
private static void TimeProc(object state, ElapsedEventArgs e)
{
Console.WriteLine("Current time {0} on the thread {1}", DateTime.Now, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(20000);
}
static void Main(string[] args)
{
Console.WriteLine("Press <Enter> for finishing\n\n");
ThreadPool.SetMaxThreads(10, 10);
System.Timers.Timer MyTimer = new System.Timers.Timer(1000);
MyTimer.Elapsed += new ElapsedEventHandler(TimeProc);
MyTimer.Start();
Console.ReadLine();
MyTimer.Stop();
}
}
가능한 출력으로 여기에있을 것입니다 :
Current time 03.02.2011 0:00:09 on the thread 4
Current time 03.02.2011 0:00:10 on the thread 5
Current time 03.02.2011 0:00:12 on the thread 6
Current time 03.02.2011 0:00:13 on the thread 7
Current time 03.02.2011 0:00:14 on the thread 8
Current time 03.02.2011 0:00:15 on the thread 9
Current time 03.02.2011 0:00:16 on the thread 10
Current time 03.02.2011 0:00:17 on the thread 11
Current time 03.02.2011 0:00:18 on the thread 12
Current time 03.02.2011 0:00:19 on the thread 13
Current time 03.02.2011 0:00:30 on the thread 4
Current time 03.02.2011 0:00:30 on the thread 5
가능한 솔루션 : 당신이 다음 테스트 프로그램 고려할 수있는이 문제에 대한 그림으로
1) 그것은 에서 영감을 얻었습니다. C# Timer vs Thread in Service
그리고 여기 샘플 위에서 언급에 대한 같은 코드가 있습니다
public class EntryPoint
{
private static System.Timers.Timer MyTimer;
private static void TimeProc(object state, ElapsedEventArgs e)
{
Console.WriteLine("Current time {0} on the thread {1}", DateTime.Now, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(20000);
MyTimer.Enabled = true;
}
static void Main(string[] args)
{
Console.WriteLine("Press <Enter> for finishing\n\n");
ThreadPool.SetMaxThreads(10, 10);
MyTimer = new System.Timers.Timer(1000);
MyTimer.AutoReset = false;
MyTimer.Elapsed += new ElapsedEventHandler(TimeProc);
MyTimer.Enabled = true;
Console.ReadLine();
}
}
2) 두 번째 방법은 SynchronizingObject의에 관한 것입니다,하지만 그것은 단지 윈도우 폼 응용 프로그램 또는 그 것 오브젝트를 구현하기위한 코드의 필요한 추가 개발을위한 가치 ISynchronizeInvoke 인터페이스를 구현해야합니다. 이 방법에 대해 자세히 알아보십시오 here
그래서 지금은 우선 해결책을 선호합니다.
:
여기당신이 타이머를 초기화하고 시작 했죠 방법 . Elapsed 이벤트를 대기열에 올려 놓는 것이 좋습니다. 하드웨어 인터럽트라면 인터벌을 날려 버릴 수 있습니다. –
데이터를 한 번만 처리해야하는 이유가 반복 타이머 인 이유는 무엇입니까? 아니면 X 시간마다 한 번만을 의미합니까? – Chris
@Chris 내 경우에는 다른 응용 프로그램이 데이터베이스에 일부 데이터를 저장하고 응용 프로그램은이를 읽고 처리해야합니다. – apros