简体   繁体   English

C#:Thread.Sleep无法正常工作

[英]C#: Thread.Sleep Not working

I have a bit of code which is meant to show a form for a period of time and play a sound. 我有一些代码,可以显示一段时间的形式并播放声音。 However the Form stays open. 但是,表格保持打开状态。

    static void Main(string[] args)
    {
        SoundPlayer sp = new SoundPlayer();
        ShowImage(@"Resources\Fish.png", "Fish", 256, 256, 1000);
        sp.SoundLocation = @"Resources\fish.wav";
        sp.Play();

    }


    public static void ShowImage(string img, string title, int width, int height, int timeout)
    {
        ImageContainer ic = new ImageContainer();
        ic.imgView.Image = Image.FromFile(img);
        ic.Text = title;
        ic.Size = ic.imgView.Image.Size;
        ic.Height = height;
        ic.Width = width;
        ic.ShowDialog();
        Thread.Sleep(timeout);
        ic.Hide();
        ic.Opacity = 0;
        ic.Dispose();
    }

It just stays with the form open doesn't close or hide. 它只是保持打开状态而不关闭或隐藏。 ImageContainer is a Form with a PictureBox called imgView in it. ImageContainer是一个窗体,其中包含一个名为imgView的PictureBox。 I need it to time out for 1 second before it closes. 我需要它在关闭之前超时1秒。

The line: 该行:

ic.ShowDialog();

Causes the form to show in a modal fashion, so that method blocks and prevents everything else from running until the form closes. 使表单以模式方式显示,从而使方法阻塞并阻止其他所有内容在表单关闭之前运行。

Change that line to: 将该行更改为:

ic.Show();

This is non-modal, and the rest of the method will complete. 这是非模式的,其余方法将完成。

ShowDialog() is modal and never returns until you close the dialog. ShowDialog()是模态的,直到关闭对话框后才返回。 You want Show(), and also you probably want to send a timer message to yourself instead of sleeping. 您需要Show(),并且您可能还想向自己发送计时器消息而不是睡觉。

Some sample code here: 一些示例代码在这里:

http://www.codeproject.com/KB/cs/A_Custom_Message_Box.aspx http://www.codeproject.com/KB/cs/A_Custom_Message_Box.aspx

Sleep never gets called when you call showdialog() the form causes the calling thread to wait until the code in the form closes the window. 当您调用showdialog()时,睡眠永远不会被调用,窗体使调用线程等待,直到窗体中的代码关闭窗口。 close the window with code in your form and things will work more like you expect. 关闭窗体中包含代码的窗口,事情将按预期运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM