睡眠/暂停 C# 中的函数 [英] Sleep / pause a function in c#

查看:35
本文介绍了睡眠/暂停 C# 中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 wp 7.x/8 制作一个应用.

I am making an app for wp 7.x/8.

有一个类似 -

public void draw()
{
    .............
    ImageBrush imgbrush = new ImageBrush();
    imgbrush.ImageSource = new BitmapImage(...);

    rect.Fill = imgbrush;  //rect is of type Rectangle that has been created 
                           //and added to the canvas
    ........
}

和另一个函数

private void clicked(object sender, RoutedEventArgs e)
{
    draw();
    ........
    if (flag)
    {
          Thread.sleep(5000);
          draw();
    }
}

但是当按钮被点击时,两个绘制操作的结果同时出现在屏幕上.

But when the button is clicked the result of both the draw operation appear simultaneously on the screen.

如何让第二次 draw() 操作的结果在延迟一段时间后出现?

How to make the result of second draw() operation to appear after some delay?

或者是否有类似屏幕缓冲区的东西,直到缓冲区没有填满屏幕才会刷新?

Or is there something like buffer for the screen, until the buffer is not filled the screen will not refresh?

在这种情况下,如何显式刷新或刷新屏幕或强制 Rectangle 的 .fill() 方法在屏幕上进行更改?

In that case, how to FLUSH or Refresh the screen explicitly or force the .fill() method of Rectangle to make the changes on the screen?

在这方面的任何帮助将不胜感激.

Any help in this regard would be highly appreciated.

推荐答案

正如pantaloons 所说,由于您的所有操作都在同一个线程上(第一次绘制、睡眠和第二次绘制),因此 UI 本身永远不会得到有机会更新.但是,有一个稍微好一点的实现(尽管它遵循与上述建议相同的原则).

As pantaloons says, since all of your actions are on the same thread (the first draw, the sleep, and the second draw), the UI itself never gets a chance to update. However, there is a slightly better implementation (though it follows the same principal as the aforementioned suggestion).

通过使用计时器,您可以让它将等待踢到另一个线程,从而允许 UI 在执行第二次绘制之前从第一次绘制更新​​,如下所示:

By using a timer, you can let it kick the wait to another thread, allowing the UI to update from the first draw before doing the second, like so:

private void clicked(object sender, RoutedEventArgs e)
{
    draw();
    ........
    if (flag)
    {
        var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };

        timer.Tick += (sender, args) => { timer.Stop(); draw(); };

        timer.Start();
    }
}

在这个方案中,所有的调用都由 DispatcherTimer 处理(它会自动回调到 UI 线程).此外,如果 draw 需要连续调用两次以上,计时器将继续计时直到停止,因此扩展以包含计数将非常简单.

In this solution, all the invocation is handled by the DispatcherTimer (which will automatically call back to the UI thread). Also, if draw needs to be called more than twice in a row, the timer will continue to tick until stopped, so it would be very straightforward to extend to include a count.

这篇关于睡眠/暂停 C# 中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆