Advertisement
Guest User

Untitled

a guest
Sep 19th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.49 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9.  
  10. namespace TimerFun
  11. {
  12.  
  13.    public partial class Form1 : Form
  14.    {
  15.  
  16.       public event EventHandler Load;
  17.      
  18.       public Form1()
  19.       {
  20.          InitializeComponent();
  21.  
  22.          Timer timer1 = new Timer();
  23.          Timer timer2 = new Timer();
  24.  
  25.          timer1.DoAfter(5, () => MessageBox.Show("5 Seconds!"));
  26.          timer2.DoAfter(8, () => MessageBox.Show("8 Seconds!"));
  27.       }
  28.      
  29.    }
  30.  
  31.  
  32.  
  33.    public static class TimerExtensions
  34.    {
  35.  
  36.       public static Dictionary<string, Action> Timers { get; set; }
  37.  
  38.       public static void DoAfter(this Timer timer, int seconds, Action action)
  39.       {
  40.          if (Timers == null)
  41.          {
  42.             Timers = new Dictionary<string, Action>();
  43.          }
  44.  
  45.          timer.Interval = seconds * 1000;
  46.          timer.Tag = Guid.NewGuid().ToString();
  47.          timer.Tick += HandleTimerTick;
  48.  
  49.          Timers.Add(timer.Tag.ToString(), action);
  50.  
  51.          timer.Enabled = true;
  52.          timer.Start();
  53.       }
  54.  
  55.       public static void HandleTimerTick(object sender, EventArgs e)
  56.       {
  57.          Timer timer = (Timer)sender;
  58.  
  59.          if (Timers.ContainsKey(timer.Tag.ToString()))
  60.          {
  61.             Action action = Timers[timer.Tag.ToString()];
  62.             action();
  63.  
  64.          }
  65.  
  66.          timer.Stop();
  67.       }
  68.  
  69.    }
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement