Skip to content

Instantly share code, notes, and snippets.

@idemax
Created May 28, 2019 15:17
Show Gist options
  • Save idemax/2105dc92890d0e702853bbe4d6070489 to your computer and use it in GitHub Desktop.
Save idemax/2105dc92890d0e702853bbe4d6070489 to your computer and use it in GitHub Desktop.
C# / CSharp Timeout util who manage many threads.
using System;
using System.Collections.Generic;
using System.Threading;
namespace Your.Namespace.Here // <=== update the namespace!
{
/// <summary>
/// Time manipulation tools.
/// </summary>
public static class TimeUtil
{
/// <summary>
/// Stack of current alive threads.
/// </summary>
private static readonly Dictionary<int, Thread> ThreadStack = new Dictionary<int, Thread>();
/// <summary>
/// Stack of actions from alive threads.
/// </summary>
private static readonly Dictionary<int, Action<bool>> ActionStack = new Dictionary<int, Action<bool>>();
/// <summary>
/// Starts a new timer based on id. If the same id is triggered, the past one is canceled.
/// </summary>
/// <param name="id"></param>
/// <param name="msTimeout"></param>
/// <param name="action"></param>
public static void StartTimer(int id, int msTimeout, Action<bool> action)
{
if (ThreadStack.ContainsKey(id)) StopTimer(id);
var timerThread = new Thread(() =>
{
Thread.Sleep(msTimeout);
RemoveThread(id, false);
TriggerAndRemoveAction(id, true);
});
ThreadStack.Add(id, timerThread);
ActionStack.Add(id, action);
timerThread.Start();
}
/// <summary>
/// Stops the timer based on its id.
/// </summary>
/// <param name="id"></param>
public static void StopTimer(int id)
{
StopTimer(id, true);
}
/// <summary>
/// Stops the timer based on its id.
/// </summary>
/// <param name="id"></param>
/// <param name="triggerAction">Trigger or not the action with FALSE argument.</param>
private static void StopTimer(int id, bool triggerAction)
{
RemoveThread(id, true);
if (!triggerAction) return;
TriggerAndRemoveAction(id, false);
}
/// <summary>
/// Trigger and removes the action from the stack.
/// </summary>
/// <param name="id"></param>
/// <param name="isFinished"></param>
private static void TriggerAndRemoveAction(int id, bool isFinished)
{
if (!ActionStack.ContainsKey(id)) return;
ActionStack[id](isFinished);
ActionStack.Remove(id);
}
/// <summary>
/// Remove the thread from the stack based on id.
/// </summary>
/// <param name="id"></param>
/// <param name="abort"></param>
private static void RemoveThread(int id, bool abort)
{
if (!ThreadStack.ContainsKey(id)) return;
if (abort) ThreadStack[id].Abort();
ThreadStack.Remove(id);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment