Update MVVM WPF BackgroundWorker and UI

I am exploring the MVVM pattern using wpf, and I am trying to create a simple splash screen to download applications.

I have a simple “Download with two properties” class that are limited by my interface.

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
}

From my ctor ViewModel I define this model

Loading = new Loading(0, "Loading...");

and run a new thread calling the GetSystemInfo () function, which takes some action to load some information.

Thread systemInfo = new Thread(GetSystemInfo);
systemInfo.IsBackground = true;
systemInfo.Start();

I am updating ui from GetSystemInfo () with

Loading.TextStatus = "Loading User Information...";
Loading.CurrentStatus = 50;

So far, so good .. the thread is updating ui correctly, but the problem is that I want to close this splashcreen and open a new window when the download is complete, but I can’t check if the thread is finished or at least I didn’t find way to do it.

Is there any way to solve this problem?

Thanks.

+4
1

, Task ( ) async-await.

, await Task, , . , , . , 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.
}
+3

All Articles