WPF Multi Threading

What you want to do is run the long running processes off the UI thread then when it is finishedupdate the UI – which the Dispatcher helps you to:

  1. Start long process on another thread and return immediately.
  2. (long process still running, UI continues to update)
  3. Long process finishes, update the UI on the UI thread.

e.g.:

    private void UpdateButtonContent(string text)
    {
        button.Content = text;
    }

    private void SimLongRunningProcess()
    {
        Thread.Sleep(2000);
    }

    private void OnProcessFinished(Task task)
    {
        string content;
        if(task.Exception != null)
        {
            content = task.Exception.Message;
        }
        else
        {
            content = "Success";
        }

        Dispatcher.BeginInvoke(new Action<string>(UpdateButtonContent), DispatcherPriority.Normal, content);
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        // Start long running process and return immediatly
        var task = Task.Factory.StartNew(SimLongRunningProcess);
        task.ContinueWith(OnProcessFinished);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *