[英]creating a UI in background thread WPF?
我試過以下:
var task = new Task(() =>
{
for (int i=0; i<10; i++) {
//Create new Grid HERE
// Add Table with some dynamic data here..
// print the above Grid here.
}
});
task.ContinueWith((previousTask) =>
{
label.Content = printerStatus(); // will return "Out of Paper", "printing", "Paper jam", etc.
},
TaskScheduler.FromCurrentSynchronizationContext());
label.Content = "Sending to printer";
它返回以下錯誤:調用線程必須是STA,因為許多UI組件需要這個..
嘗試創建新的UI對象Grid時發生錯誤。
我怎樣才能解決這個問題? 如果還有其他任何方式讓我知道!
任務使用MTA中的線程池線程。
如果您需要后台STA線程,則必須自己創建一個並明確設置ApartmentState
。
Thread t = new Thread( ... );
t.SetApartmentState( ApartmentState.STA );
t.Start();
使用Dispatcher作為標簽和Invoke可能會有所幫助:
label.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
label.Content = printerStatus();
}
));
您不能在與主UI線程不同的線程上創建UI對象,因為只要將它們添加到UI,它就會嘗試設置Parent
屬性,並且WPF中的線程無法修改在不同線程上創建的對象。
相反,我建議在第二個線程上創建Grid的數據列表或集合,並使用類似ItemsControl
東西將其綁定到UI。 這將使所有UI對象保留在主UI線程上,而后台處理可以在后台線程上完成。
要從后台線程(例如狀態標簽)更新UI對象,我建議使用Dispatcher
如lawrencealan的回答所示。 Dispatcher
是WPF的主UI線程的內部消息隊列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.