Home > Net > How to solve the System. The Timers. The Timer thread unlimited increase cyclic query.
How to solve the System. The Timers. The Timer thread unlimited increase cyclic query.
Time:09-22
Using System. The Timers. The Timer to do a query regularly, because it is called a third-party DLL in the query interface, sometimes only the next query interface doesn't return results, lead to the Timer query each time the loop will generate a thread will not be turned off, the last crash directly, what's the solution?
CodePudding user response:
{ Private int processInProgress=0; Private void Timer_Elapsed (object sender, ElapsedEventArgs e) { If (System.Threading.Interlocked.Com pareExchange (ref processInProgress, 1, 0).=0) { System. Diagnostics. Debug. WriteLine (" the current process is not over, ignore the timer event, "); return; } Try { //here to write you now processing routines } The finally { Interlocked. Exchange (ref processInProgress, 0); } } }
CodePudding user response:
If Interlocked.Com pareExchange bad to understand, you can also use a lock:
{ Private readonly object lockObj=new object (); Private bool processInProgress=false; Private void Timer_Elapsed (object sender, ElapsedEventArgs e) { The lock (lockObj) { If (processInProgress) { System. Diagnostics. Debug. WriteLine (" the current processing is still in operation, ignore the timer event, "); return; } ProcessInProgress=true; } Try { //here to write you now processing routines } The finally { The lock (lockObj) processInProgress=false; } } }
CodePudding user response:
You every time is to create a thread? You can try the thread pool,