C# Timer执行方法

private void button3_Click(object sender, EventArgs e)
{
System.Timers.Timer t = new System.Timers.Timer(500); //实例化Timer类,设置间隔时间为XX毫秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(theout); //到达时间的时候执行事件;
t.AutoReset = true; //设置是执行一次(false)还是一直执行(true);
t.Enabled = true; //是否执行System.Timers.Timer.Elapsed事件;

}

/// <summary>
/// 通过原子来判断是否有锁(1代表没有锁,0代表锁)
/// 原子锁跟lock锁相比就是,不会因为其他线程锁住,而阻塞,如果发现锁住就直接跳过。
/// </summary>
public static int iobject = 1;
//递增的值(用来测试的数据)
public static int itestobj = 0;

/// <summary>
/// 调用的事件
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>

public void theout(object source, System.Timers.ElapsedEventArgs e)
{
//原子的值
if (iobject == 1)
{
//该表原子的值让这个变成锁
Interlocked.Exchange(ref iobject, 0);
//模拟真实的方法
Thread.Sleep(200);
Console.WriteLine(itestobj.ToString());
itestobj = itestobj + 1;

//释放锁
Interlocked.Exchange(ref iobject, 1);
}
else
{
//已经锁住就直接跳过。
return ;
}

}

原文地址:https://www.cnblogs.com/zhian/p/5041002.html