简体   繁体   中英

C# showing textbox in UI, stopping main thread and then resuming

I am having a little trouble doing something which should be simple, I am using a simple graphical interface to show data coming from a kinect sensor, and I want to create a transition, that is, I want to show the user a video and then I want the program to resume its operation. My code goes like this:

  private void OnTimedEvent(object sender, ElapsedEventArgs e)
    {



         Random random = new Random();
         int periodo=random.Next(9000,20000); 
         contador.Interval = periodo;

         this.Dispatcher.Invoke(new Action(CreateTextBox),null);
         this.Dispatcher.Invoke(new Action(StopThread), null);
         this.Dispatcher.Invoke(new Action(Advance), null);
         this.Dispatcher.Invoke(new Action(ResetTime), null); 
         this.Dispatcher.Invoke(new Action(ShowSample), null);
    }

This creates a timer with a random time between 9 and 20 seconds. After that I want to do a series of things, which are: Showing a message in the UI Stopping all activities in the UI Showing a video in the UI Resetting a variable Showing a Video sequence

and the functions used are:

   private void CreateTextBox() {

        TextBox textBox = new TextBox { 
        FontSize=40,
        };

        textBox.Text = "Siguiente Actividad";
        canvas2.Children.Add(textBox);           

        // System.Threading.Thread.Sleep(1000);

    }

 private void ResetTime() {
        contadorsegundos = 0;

    }

  private void StopThread(){
         System.Threading.Thread.Sleep(8000);
    }

   private void ShowSample() {
        canvas2.Children.Clear();
        MediaElement mediaElement2 = new MediaElement();
        canvas2.Children.Add(mediaElement2);
        string location = "C:\\Users\\PALMA\\Documents\\Visual Studio 2010\\Projects\\Interfaz\\Interfaz\\Videos\\ejercicio1.mp4";
        try
        {
            mediaElement2.Source = new Uri(location);
            mediaElement2.Play();
            //MessageBox.Show(final);
        }
        catch
        {
            //no se atiende la excepción 
            //MessageBox.Show("Not Found");
        }

    }

What happens is that the main thread stops for 8 seconds, but the texbox was never shown, even though the function CreateTextBox was called before the function StopThread, I was expecting that the message would be shown and then the thread would stop.

Any help will be much appreciated.

Instead of putting the main thread to sleep for 8 seconds, you should use:

await Task.Delay(8000);

This way you avoid freezing the main thread, which can cause all kinds of unpredictable problems.

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