Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the nextgen-gallery-pro domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/mxvysmpn/public_html/wp-includes/functions.php on line 6121
WPF – Running long tasks without freezing the UI | WPF – Running long tasks without freezing the UI – { Dev Farm }

{ 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 *.