【问题标题】:C# showing textbox in UI, stopping main thread and then resumingC# 在 UI 中显示文本框,停止主线程然后恢复
【发布时间】:2014-07-25 19:58:32
【问题描述】:

我在做一些应该很简单的事情时遇到了一点麻烦,我正在使用一个简单的图形界面来显示来自 kinect 传感器的数据,并且我想创建一个过渡,也就是说,我想向用户展示一个视频,然后我希望程序恢复运行。我的代码是这样的:

  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);
    }

这会创建一个随机时间在 9 到 20 秒之间的计时器。之后我想做一系列的事情,它们是: 在 UI 中显示消息 停止 UI 中的所有活动 在 UI 中显示视频 重置变量 显示视频序列

使用的功能有:

   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");
        }

    }

发生的情况是主线程停止了 8 秒,但从未显示过 texbox,即使在函数 StopThread 之前调用了函数 CreateTextBox,我希望显示消息然后线程会停止。

任何帮助将不胜感激。

【问题讨论】:

  • 你不应该让 UI 线程进入睡眠状态。这会导致显示器发生各种不可预知的事情,并且还会使程序对键盘和鼠标没有响应。

标签: c# multithreading user-interface


【解决方案1】:

您应该使用以下命令,而不是让主线程休眠 8 秒:

await Task.Delay(8000);

这样可以避免冻结主线程,这会导致各种不可预知的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多