简体   繁体   中英

Thread.Sleep is not working as expected in Windows Forms C#

I have an application that uses a timer to 1 in 1 minute perform refresh data in a DataGridView. Depending on the information to return the screen, a different sound will play. Each sound has a playback time. I am using this command to have the effect of duration of my music.

Thread.sleep(GetMusicDuration[i] * 1000);

When I start my application the first time, everything goes well, but when the timer runs TICK event that carries the information in the DataGridView again and run PLAY to play the sounds my Thread.Sleep command does not work, it simply ignores not expect the time set for parameter.

public void PlaySound()
    {
        try
        {
            while (1 == 1)
            {
                List<string> distinctMusic = GetMusicFile.Distinct().ToList();
                StopSound();
                if (distinctMusic.Count > 0)
                {
                    for (int i = 0; i < distinctMusic.Count; i++)
                    {
                        player.SoundLocation = distinctMusic[i];
                        player.Play();
                        Thread.Sleep(GetMusicDuration[i] * 1000);
                        StopSound();
                    }
                }

                DisposePlayer();
            }
        }
        catch (Exception e)
        {
            if (generateLog)
                log.LogTxt(e.ToString());
        }
    }

Until now I did not understand why the exucução wrong.

someone could help me?

thank you...!

Thread.Sleep blocks the UI thread. You should use a timer in stead:

//Create a new timer that ticks every xms
var t = new System.Timers.Timer (GetMusicDuration[i] * 1000);

//When a tick is elapsed
t.Elapsed+=(object sender, System.Timers.ElapsedEventArgs e) => 
{
   //what ever you want to do
};
//Start the timer
t.Start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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