【问题标题】:Thread.Sleep() in C#C# 中的 Thread.Sleep()
【发布时间】:2012-08-20 14:36:11
【问题描述】:

我想在 C# Visual Studio 2010 中制作一个图像查看器,它会在几秒钟后一张一张地显示图像:

i = 0;

if (image1.Length > 0) //image1 is an array string containing the images directory
{
    while (i < image1.Length)
    {
        pictureBox1.Image = System.Drawing.Image.FromFile(image1[i]);
        i++;
        System.Threading.Thread.Sleep(2000);
    }

当程序启动时,它会停止并只显示第一张和最后一张图片。

【问题讨论】:

  • 你阻塞了 UI 线程..
  • 你总是覆盖 pictureBox1.Image
  • 我猜它在中间睡着 ;) - Thread.Sleep(123) 停止整个线程,在这种情况下包括图像显示,我猜想不知道你周围的代码 - 但是,使用 Timer 可能会给你带来更多的运气
  • 不确定你为什么被否决?对我来说似乎是个好问题。
  • 和@Chad 一样的感觉,+1 给 OP。

标签: c# winforms


【解决方案1】:

Thread.Sleep 会阻止您的 UI 线程改用 System.Windows.Forms.Timer。

【讨论】:

  • 使用 System.Windows.Forms.Timer 有什么特殊原因吗?
  • @ChriPf 因为 Windows 窗体计时器滴答事件自动在 UI 线程上运行。无需调用。
  • 解释:windows在重绘时显示图片。重绘是一个 UI 线程事件。您阻止线程,没有 UI 更新 - 也没有其他 UI 交互,所以没有按钮点击等。
【解决方案2】:

使用计时器。

首先声明您的 Timer 并将其设置为每秒计时一次,计时时调用 TimerEventProcessor。

static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Interval = 1000;
myTimer.Start();

您的类将需要 image1 数组和一个 int 变量 imageCounter 来跟踪 TimerEventProcessor 函数可访问的当前图像。

var image1[] = ...;
var imageCounter = 0;

然后写下你想在每个刻度上发生的事情

private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) {
    if (image1 == null || imageCounter >= image1.Length)
        return;

    pictureBox1.Image = Image.FromFile(image1[imageCounter++]);
}

这样的事情应该可以工作。

【讨论】:

  • 我在 Visual Studio Mac 类上看不到 System.Windows.Form.Timer。有 System.Threading.Timer 但语法不同。
【解决方案3】:

是的,因为Thread.Sleep 在 2s 期间阻塞了 UI 线程。

改用计时器。

【讨论】:

    【解决方案4】:

    如果您想避免使用 Timer 并定义事件处理程序,您可以这样做:

    DateTime t = DateTime.Now;
    while (i < image1.Length) {
        DateTime now = DateTime.Now;
        if ((now - t).TotalSeconds >= 2) {
            pictureBox1.Image = Image.FromFile(image1[i]);
            i++;
            t = now;
        }
        Application.DoEvents();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 2012-07-29
      • 1970-01-01
      相关资源
      最近更新 更多