解决Timer中的重入现象(录制GIF的过程中出现的问题)

在多线程下给inTimer赋值不够安全,Interlocked.Exchange提供了一种轻量级的线程安全的给对象赋值的方法(感觉比较高上大,也是比较推荐的一种方法)。

private static int inTimer = 0; 
/// <summary>
/// System.Timers.Timer的回调方法
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private static void TimersTimerHandler(object sender, EventArgs args)
{
    int t = ++num;
    if (Interlocked.Exchange(ref inTimer, 1) == 0)
    {
        Console.WriteLine(string.Format("线程{0}输出:{1},       输出时间:{2}", t, outPut.ToString(), DateTime.Now));
        System.Threading.Thread.Sleep(2000);
        outPut++;
        Console.WriteLine(string.Format("线程{0}自增1后输出:{1},输出时间:{2}", t, outPut.ToString(), DateTime.Now));
        Interlocked.Exchange(ref inTimer, 0); 
    }
}
Last modification:July 16th, 2019 at 12:39 am
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment