wpf - 如何将 DispatcherTimer 设置到 for 循环中

标签 wpf multithreading

我正在使用 wpf DispatcherTimer,我想将它使用到 for 循环中,我如何使用它..

我的代码在这里..

        DispatcherTimer timer = new DispatcherTimer();

        timer.Tick += (s, e) =>
        {
            for (i = 0; i < 10; i++)
            {
                obsValue.Add(new Entities(i));
                timer.Interval = TimeSpan.FromSeconds(30);
                timer.Start();
            }
        };

谢谢......

最佳答案

当您启动计时器并将 Interval 设置为 30 秒时,其 Tick 事件将每 30 秒引发一次。

现在,我从你的问题中了解到,你想每 30 秒添加一条记录。

这是您可以执行的操作。请注意,它不需要 for 循环,但您仍然需要维护当前索引。为此,您可以使用私有(private)字段带有 lambda 的局部变量

示例:

    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(30);
    
    Int32 index = 0, maxValue = 10;

    timer.Tick += (s, e) =>
    {                
        obsValue.Add(new Entities(index));
        index ++; // increment index

        // Stop if this event has been raised max number of times
        if(index > maxValue) timer.Stop();
    };

    timer.Start();

关于wpf - 如何将 DispatcherTimer 设置到 for 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4544147/

相关文章:

wpf - 当文本框通过选项卡聚焦时光标不显示

c# - Windows 7 更新,导致 WPF 应用程序中出现 "Item has already been added. Key in dictionary: controlbrush"

ios - 工作完成前 dispatch 组通知

java - 如何跨服务器可靠地杀死@Scheduled 线程?

c# - 使用 WebKit 在 Windows 上模拟 iOS 和 Android 内置浏览器

wpf - WPF Ribbon 可以在没有办公室的机器上工作吗?

c# - MVVM MEF WindowFormHost

c - 将大型多线程二进制文件拆分为较小的单个进程/二进制文件

multithreading - 用于基于 opencv 的图像处理的基于信号量的同步

c# - 使用线程安全更新单例的属性