如何计算滴答事件发生的次数?

时间:2013-11-11 20:33:58

标签: c# .net wpf

我真的想做什么,我想计算滴答事件发生的次数。实际上我想检查一下,如果这个事件发生了5次。 然后应显示消息框。 这是我的代码:

public partial class MainWindow : Window
{
    int i = 0;
    int points = 0;
    int counter = 0;

    public MainWindow()
    {            
      System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
      dispatcherTimer.Tick += new EventHandler(this.playMyAudioFile);

      TimeSpan ts = dispatcherTimer.Interval = new TimeSpan(0, 0, 2);

      dispatcherTimer.Start();
      if (counter == 5)
      {
        dispatcherTimer.Stop();            
      }

      InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        // some code    
        label1.Content = points;
        }
    }

    private void playMyAudioFile(object sender, EventArgs e)
    {
        Random rd = new Random();            
        i = rd.Next(1, 26);            
        mediaElement1.Source = new Uri(@"D:\Project C#\A-Z\" + i + ".mp3");
        mediaElement1.Play();
    }
}

2 个答案:

答案 0 :(得分:1)

使用await代替计时器,使这项特殊任务变得更加容易:

public static async Task makeMusic(TimeSpan timespan)
{
    for (int i = 0; i < 5; i++)
    {
        //this assumes you can remove the parameters from this method
        playMyAudioFile(); 
        await Task.Delay(timespan);
    }

    MessageBox.Show("All done!");
}

如果需要配置,您可以将计数作为参数,或者如果需要永远不更改,则将timespan作为参数删除。

答案 1 :(得分:0)

Servy的解决方案比使用计时器更清洁。但如果你坚持使用计时器,我会建议:

private int counter = 0;
private Random rd = new Random();
private void playMyAudioFile(object sender, EventArgs e)
{
    i = rd.Next(1, 26);            
    mediaElement1.Source = new Uri(@"D:\Project C#\A-Z\" + i + ".mp3");
    mediaElement1.Play();
    ++counter;
    if (counter == 5)
    {
        dispatcherTimer.Stop();
    }
}

认为 sender是调度程序计时器,所以你可以写:

var timer = (DispatcherTimer)sender;
timer.Stop();

而且,请替换它:

TimeSpan ts = dispatcherTimer.Interval = new TimeSpan(0, 0, 2);

使用:

TimeSpan ts = dispatcherTimer.Interval = TimeSpan.FromSeconds(2);

当我看到new TimeSpan(0, 0, 2)时,我必须考虑一下这意味着什么。是分钟,秒和毫秒?天,小时和分钟?小时,分钟和秒?

但是,{p> TimeSpan.FromSeconds(2)是明确的。绝对没有歧义。