using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//No UI thread issue, use SetTimeout(cb, delay)
SetTimeout(() =>
{
MessageBox.Show("First");
}, 2000);
SetTimeout(() =>
{
listBox1.Items.Add("Second");
}, 4000, this);
Guid hnd = SetTimeout(() =>
{
listBox1.Items.Add("Third");
}, 6000, this);
SetTimeout(() =>
{
listBox1.Items.Add("Forth");
}, 8000, this);
ClearTimeout(hnd);
}
#region SetTimeout/ClearTimeout Simulation
//Dictionary for running setTimeout
static Dictionary<Guid, Thread> _setTimeoutHandles =
new Dictionary<Guid, Thread>();
//SetTimeout for no UI Thread issue
static Guid SetTimeout(Action cb, int delay)
{
return SetTimeout(cb, delay, null);
}
//Javascript-style SetTimeout function
//remember to set uiForm argument when there cb is trying
//to change UI controls in window form
//it will return a GUID as handle for cancelling
static Guid SetTimeout(Action cb, int delay, Form uiForm)
{
Guid g = Guid.NewGuid();
Thread t = new Thread(() =>
{
Thread.Sleep(delay);
_setTimeoutHandles.Remove(g);
if (uiForm != null)
//use Invoke() to avoid threading issue
//Ref: http://tinyurl.com/yjckzhz
uiForm.Invoke(cb);
else
cb();
});
_setTimeoutHandles.Add(g, t);
t.Start();
return g;
}
//Javascript-style ClearTimeout
static void ClearTimeout(Guid g)
{
if (!_setTimeoutHandles.ContainsKey(g))
return;
_setTimeoutHandles[g].Abort();
_setTimeoutHandles.Remove(g);
}
#endregion
}
}