定时器故障。 。

时间:2013-03-02 13:27:06

标签: c# wpf visual-studio-2010 kinect

我正在尝试在wpf vs 2010中创建一个按钮,点击后会定期执行操作,我在这个和其他网站上看了很多不同的类似问题,但问题是我试图打电话从kinect获取屏幕截图的功能,可以让计时器工作,但它保持冻结,而不是10个不同的屏幕截图,间隔2.5秒我一次又一次得到相同的屏幕截图,任何帮助非常感谢。 目前我正在使用复选框而不是按钮,根据我在这里找到的一些提示。

    private void checkBox1_Checked_1(object sender, RoutedEventArgs e)
    {

        Stopwatch stopwatch = new Stopwatch();

        // Begin timing
        stopwatch.Start();

        // Do something
        for (int i = 0; i < 60000; i++)
        {
            Thread.Sleep(3);
        }

        // Stop timing
        stopwatch.Stop();

        take_motions();
    }

3 个答案:

答案 0 :(得分:1)

使用此代码,您将阻止主应用程序线程。这可以解释为什么你一遍又一遍地获得相同的屏幕截图。

您需要做的是在后台线程中启动计时器,然后形成该线程将事件发送到主应用程序以截取屏幕截图。这将允许应用程序继续工作。

为此,您应该使用其中一个Timer类。它们的工作方式略有不同,但是所有这些都应该允许您指定在计时器的每个刻度上调用的方法。

您需要将事件发送回UI以避免交叉线程问题。

答案 1 :(得分:1)

您应该使用计时器并在单独的线程中运行take_motions();

aTimer = new System.Timers.Timer(10000);

// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;

private void checkBox1_Checked_1(object sender, RoutedEventArgs e)
{
  //here call timer start or stop
}

private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    ThreadPool.QueueUserWorkItem(delegate
   {
     take_motions();
   });
}

答案 2 :(得分:0)

WPF中有一个专门的计时器类,可以避免在UI线程中运行时出现任何UI交叉线程问题。这是DispatcherTimer类:

private DispatcherTimer timer;

public MainWindow()
{
    InitializeComponent();

    timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2.5) };
    timer.Tick += timer_Tick;
}

private void timer_Tick(object sender, EventArgs e)
{
    // take screenshot here
}

private void checkBox_Checked(object sender, RoutedEventArgs e)
{
    timer.Start();
}

private void checkBox_Unchecked(object sender, RoutedEventArgs e)
{
    timer.Stop();
}
相关问题