[英]MVVM WPF BackgroundWorker and UI update
我正在學習使用wpf的MVVM模式,我正在嘗試創建一個簡單的啟動畫面來加載應用程序。
我有一個名為Loading的簡單類,它有兩個屬性,它們與我的界面有關。
public class Loading : INotifyPropertyChanged
{
/// <summary>
/// Define current status value from 0 to 100.
/// </summary>
private int _currentStatus;
/// <summary>
/// Define current status text.
/// </summary>
private string _textStatus;
/// <summary>
/// Define constructor.
/// </summary>
public Loading(int status, string statusText)
{
_currentStatus = status;
_textStatus = statusText;
}
public int CurrentStatus
{
get { return _currentStatus; }
set
{
_currentStatus = value;
OnPropertyChanged("CurrentStatus");
}
}
public string TextStatus
{
get { return _textStatus; }
set
{
_textStatus = value;
OnPropertyChanged("TextStatus");
}
}
#region Interfaces
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
從我的ctor ViewModel我實現這個模型
Loading = new Loading(0, "Loading...");
並運行一個新線程調用函數GetSystemInfo(),它執行一些東西以加載一些信息。
Thread systemInfo = new Thread(GetSystemInfo);
systemInfo.IsBackground = true;
systemInfo.Start();
我正在用GetSystemInfo()更新ui
Loading.TextStatus = "Loading User Information...";
Loading.CurrentStatus = 50;
到目前為止很好..線程正確更新ui但問題是我希望關閉此啟動畫面並在加載完成時打開一個新窗口但我無法檢查線程是否完整或至少我沒有辦法做到這一點。
有什么辦法可以解決這個問題嗎?
謝謝。
通過使用Task
類(通過任務並行庫 )和async-await
的組合,您可以輕松實現此目的。
await
Task
時發生的事情是控制權被回饋給調用者。 在您的情況下,調用者來自UI線程,因此控件將返回到UI消息循環,讓您的應用程序響應。 一旦線程完成它的工作,它將返回到await
之后的下一行,然后您可以在那里打開啟動屏幕。
它看起來像這樣:
public async void MyEventHandler(object sender, EventArgs e)
{
await Task.Run(() => GetSystemInfo());
// Here, you're back on the UI thread.
// You can open a splash screen.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.