{ Dev Farm }

Web & Windows Development

WPF – Running long tasks without freezing the UI

| 0 commenti

In orther to avoid freezed ui and annoing “Application is Not Responding” messages I made this very easy helper.
It simply set the cursor in Waiting mode and call your function on anoter task, without freezing your wpf app. When the function is done, cursor return to default.

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;
using System.Threading.Tasks;
using System.Windows.Controls;

public static class UIHelper
{

  public static void callAsync(UserControl el, Action<Object> action)
  {
    el.Cursor = Cursors.Wait;
    var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
    Task.Factory.StartNew(action, TaskCreationOptions.LongRunning).ContinueWith(_ => el.Cursor = Cursors.Arrow, uiScheduler);
  }

}

You can call the function from your UserColtrols like this:


  UIHelper.callAsync(this, o => test("hello"));

Than, if you want to update your UI from the task, you have to ask the Dispatcher, here a sample:

  private void test(string msg)
  {
    // your code...
    // your code...
    // your code...

    this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
      yourTextBox1.Text = msg;
    }));
  }

Lascia un commento

I campi obbligatori sono contrassegnati con *.