1

how are you?

I need to use two commands in my application, however, need to be performed with a time interval between them.

I tried using thread to solve my problem, but could not.

This is the code:

protected void PlaySound()
    {
        List<string> distinctMusic = Music.GetMusicFile.Distinct().ToList();
        Thread thrd = new Thread(ThreadTimerMusic);

        for (int i = 0; i < distinctMusic.Count; i++)
        {
            ScriptManager.RegisterClientScriptBlock(Page, GetType(), "playSound", "playSound('" + distinctMusic[i] + "')", true);
            thrd.Start(); //Timer
            ScriptManager.RegisterClientScriptBlock(Page, GetType(), "stopSound", "stopSound()", true);
            i++;
        }
    }
 //Timer 5 seconds.
 public  void ThreadPlayMusic()
    {
        Thread.Sleep(5000);
    }

Can anyone help me?

Thank you !

Flávio Costa
  • 895
  • 5
  • 18
  • 41
  • I'm good, thanks. And yes, I'm sure somebody here can help you. (I think I've successfully answered both questions in the actual post) – Justin Niessner Jun 24 '13 at 17:11
  • So what is happening when you run your code? Is it not sleeping for 5 seconds? – Garrison Neely Jun 24 '13 at 17:24
  • No, it performs the following code then. I also found it strange not work. – Flávio Costa Jun 24 '13 at 17:27
  • 1
    You're mixing two different things: what happens on the client, the execution of the scripts play/stop, and what happens on the server, the creation of these scripts. So as your code is run on the client you need to sleep in the client using some Javascript: have a look at http://stackoverflow.com/questions/1447407/whats-the-equivalent-of-javas-thread-sleep-in-javascript for an equivalent of *Sleep*. – Pragmateek Jun 24 '13 at 18:08
  • 1
    ScriptManager.RegisterClientScriptBlock(Page, GetType(), "sleepTime", "setTimeout(function() {stopSound();}," + Music.GetMusicDuration[i] * 1000 + ");", true); Thanks man.. works ! – Flávio Costa Jun 24 '13 at 19:24
  • Ok I'll add an answer to ease future references. :) – Pragmateek Jun 24 '13 at 19:41

1 Answers1

0

For future reference here is an expanded version of my comment. :)

The issue was: the code (Javascript) responsible for playing/stopping the music is executed on the client.

RegisterClientScriptBlock runs on the server and only generates the above script, so delaying on the server side the second part of the script would only make the client code generation longer without any effect on the way it works on the client.

The solution is to implement the delay inside the client code itself, in Javascript.

The standard way to mimic a Sleep is using the setTimeout function, so here is the final code:

ScriptManager.RegisterClientScriptBlock(Page, GetType(), "sleepTime",
"setTimeout(function() {stopSound();}," + Music.GetMusicDuration[i] * 1000 + ");", true);
Pragmateek
  • 13,174
  • 9
  • 74
  • 108