C# 中的 Thread.Sleep()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12039695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 20:10:43  来源:igfitidea点击:

Thread.Sleep() in C#

c#winforms

提问by Alyafey

I want to make an image viewer in C# Visual Studio 2010which displays images one by one after seconds:

我想在 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);
    }

When the program starts, it stops and just shows me the first and last image.

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

采纳答案by L.B

Thread.Sleep blocks your UI thread use System.Windows.Forms.Timerinstead.

Thread.Sleep 阻止您的 UI 线程使用System.Windows.Forms.Timer代替。

回答by ken2k

Yes, because Thread.Sleepblocks the UI thread during the 2s.

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

Use a timer instead.

改用计时器。

回答by CaffGeek

Use a Timer.

使用定时器。

First declare your Timer and set it to tick every second, calling TimerEventProcessorwhen it ticks.

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

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

Your class will need the image1 array and an int variable imageCounterto keep track of the current image accessible to the TimerEventProcessor function.

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

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

Then write what you want to happen on each tick

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

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

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

Something like this should work.

像这样的事情应该有效。

回答by d3dave

If you want to avoid using Timerand defining an event handler you can do this:

如果您想避免使用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();
}