[英]C# showing textbox in UI, stopping main thread and then resuming
我在做一些應該很簡單的事情時遇到了一些麻煩,我正在使用一個簡單的圖形界面來顯示來自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秒鍾,但是,即使在函數StopThread之前調用了CreateTextBox函數,也從未顯示過texbox,我期望消息會顯示出來,然后線程會停止。
任何幫助都感激不盡。
而不是讓主線程進入休眠狀態8秒鍾,您應該使用:
await Task.Delay(8000);
這樣,您可以避免凍結主線程,否則可能導致各種無法預料的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.