C# 精确显示标签 X 秒并隐藏它 Y 秒

标签 c# .net multithreading timer synchronization

<分区>

我正在为一个应该精确地使单词标签闪烁的表单编写代码。 它使用“expositionTime”来显示标签 X 毫秒,并使用“intervalTime”来将其隐藏 Y 毫秒

该过程将重复 Z 次“numExpositions”,并在单击按钮后开始。 我的代码运行没有错误,我使用两个计时器来完成这项工作。 问题是在一些说明之后计时器变得不同步

我的问题是是否有一个解决方案可以给我精确的时间同步,其中展示时间(显示标签)和间隔(隐藏)将一起开始和结束 - 可能在单独的线程上使用定时器流逝或监控等待和如何实现它们。

我的部分代码使用了两个计时器:

private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Timer timer2;
private static int counter = 0;
private static int numExpositions = 16;
private static int expositionTime = 2000;
private static int intervalTime = 1800;

// starts both timers that get desynchronized after some time 
private void button1_Click(object sender, EventArgs e) { startTimer1(); startTimer2(); }

public void startTimer1()
{
        timer1 = new System.Windows.Forms.Timer() { Interval = expositionTime + intervalTime };
        timer1.Tick += new EventHandler(OnTimer1Event);
        timer1.Start();
}

public void startTimer2()
{
        timer2 = new System.Windows.Forms.Timer() { Interval = intervalTime };
        timer2.Tick += new EventHandler(OnTimer2Event);
        timer2.Start();
}

private void OnTimer1Event(object sender, EventArgs e)
{
    if (counter >= numExpositions) // stops timers
        {
            timer1.Stop();
            timer2.Stop();
            wordLabel.Visible = false;
            counter = 0;
            this.Close()
        }
        else
        {
            wordLabel.Visible = true; // shows wordLabel
        }
    }

private void OnTimer2Event(object sender, EventArgs e)
{
    wordLabel.Visible = false; // hides wordLabel
}

最佳答案

更好的方法是这样的:

private async Task DoIt()
{
    for(int i = 0 ; i < numExpositions; i++)
    {
        wordLabel.Visible = true;
        await Task.Delay(expositionTime); //expositionTime is the number of milliseconds to keep the label visible
        wordLabel.Visible = false;
        await Task.Delay(intervalTime); //intervalTime is the number of milliseconds to keep the label hidden
    }

}

private void button1_Click(object sender, EventArgs e)
{
    DoIt();
}

这需要您使用 .NET Framework 4.5 或更高版本。

关于C# 精确显示标签 X 秒并隐藏它 Y 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33925903/

相关文章:

c# - 正则表达式:C# 提取双引号内的文本

c# - 在 .Net C# 中将 MS word 文件转换为图像

c# - 更改 InputLanguage 有什么作用?

c# - MVC 中下拉列表的 if else 条件

c# - Intellisense 不适用于 VS2010 中的一个特定项目

c# - 透视图像失真

c++ - 共享内存中的 std::mutex 不工作

python - 线程中的按引用传递可变变量

java - 在后台任务 javafx 中执行进度指示器

c# - 必须在控制离开当前方法之前分配 out 参数