Skip to content

Instantly share code, notes, and snippets.

@solrevdev
Last active January 27, 2020 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solrevdev/60f58cc72b3576617486162470c50280 to your computer and use it in GitHub Desktop.
Save solrevdev/60f58cc72b3576617486162470c50280 to your computer and use it in GitHub Desktop.
A System.Theading.Timer example that waits for a long running process to finish
using System;
using System.Threading;
public class TimerTest : IDisposable
{
private readonly Timer _timer;
private readonly object _locker = new object();
public TimerTest()
{
_timer = new Timer(new TimerCallback(TickTimer), null, 1000, 1000);
}
private void TickTimer(object state)
{
// keep GC from collecting and stopping timer;
GC.KeepAlive(_timer);
// do not let another tick happen if we are still doing things - https://stackoverflow.com/a/13267259/2041
if (Monitor.TryEnter(_locker))
{
try
{
// do long running work here
DoWork();
}
finally
{
Monitor.Exit(_locker);
}
}
}
private void DoWork()
{
Console.WriteLine("Starting DoWork()");
Thread.Sleep(2000);
Console.WriteLine("Ending DoWork()");
}
public void Dispose()
{
_timer?.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment