如何在单独的线程上在Converter中运行代码,以便UI不会冻结?

时间:2011-07-01 00:43:13

标签: c# wpf multithreading data-binding ivalueconverter

我有一个很慢的WPF转换器(计算,在线提取等)。如何异步转换以便我的UI不会冻结?我找到了这个,但解决方案是将转换器代码放在属性 - http://social.msdn.microsoft.com/Forums/pl-PL/wpf/thread/50d288a2-eadc-4ed6-a9d3-6e249036cb71中 - 我宁愿不这样做。

以下是演示此问题的示例。这里的下拉列表将冻结,直到睡眠过去。

namespace testAsync
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Windows;
    using System.Windows.Data;
    using System.Windows.Threading;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            MyNumbers = new Dictionary<string, int> { { "Uno", 1 }, { "Dos", 2 }, { "Tres", 3 } };

            this.DataContext = this;           
        }

        public Dictionary<string, int> MyNumbers
        {
            get { return (Dictionary<string, int>)GetValue(MyNumbersProperty); }
            set { SetValue(MyNumbersProperty, value); }
        }
        public static readonly DependencyProperty MyNumbersProperty =
            DependencyProperty.Register("MyNumbers", typeof(Dictionary<string, int>), typeof(MainWindow), new UIPropertyMetadata(null));


        public string MyNumber
        {
            get { return (string)GetValue(MyNumberProperty); }
            set { SetValue(MyNumberProperty, value); }
        }
        public static readonly DependencyProperty MyNumberProperty = DependencyProperty.Register(
            "MyNumber", typeof(string), typeof(MainWindow), new UIPropertyMetadata("Uno"));
    }

    public class AsyncConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            object result = null;


            if (values[0] is string && values[1] is IDictionary<string, int>)
            {
                DoAsync(
                    () =>
                        {
                                            Thread.Sleep(2000); // Simulate long task
                            var number = (string)(values[0]);
                            var numbers = (IDictionary<string, int>)(values[1]);

                            result = numbers[number];
                            result = result.ToString();
                        });
            }

            return result;
        }

        private void DoAsync(Action action)
        {
            var frame = new DispatcherFrame();
            new Thread((ThreadStart)(() =>
            {
                action();
                frame.Continue = false;
            })).Start();
            Dispatcher.PushFrame(frame);
        }

        public object[] ConvertBack(object value, Type[] targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }

和XAML:

<Window x:Class="testAsync.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:testAsync"
        Title="MainWindow" Height="200" Width="200">
    <Window.Resources>
        <local:AsyncConverter x:Key="asyncConverter"/>
    </Window.Resources>
    <DockPanel>
        <ComboBox DockPanel.Dock="Top" SelectedItem="{Binding MyNumber, IsAsync=True}"                   
                  ItemsSource="{Binding MyNumbers.Keys, IsAsync=True}"/>
        <TextBlock DataContext="{Binding IsAsync=True}"
            FontSize="50" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBlock.Text>
                <MultiBinding Converter="{StaticResource asyncConverter}">
                    <Binding Path="MyNumber" IsAsync="True"/>
                    <Binding Path="MyNumbers" IsAsync="True"/>
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </DockPanel>
</Window>

请注意,所有Bindings现在都是IsAsync =“True”,但这没有帮助。

enter image description here

组合框将卡住2000毫秒。

4 个答案:

答案 0 :(得分:6)

我知道你说你不想从属性设置器中调用翻译,但我认为它比IValueConverter / IMultiValueConverter更清晰。

最终,您想要从组合框中设置所选数字的值,并立即从中返回。您希望推迟更新显示/翻译的值,直到翻译过程完成。

我认为对数据进行建模更加清晰,使得转换后的值本身就是一个只能由异步进程更新的属性。

    <ComboBox SelectedItem="{Binding SelectedNumber, Mode=OneWayToSource}"                   
              ItemsSource="{Binding MyNumbers.Keys}"/>
    <TextBlock Text="{Binding MyNumberValue}" />

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();

        MyNumbers = new Dictionary<string, int> { { "Uno", 1 }, { "Dos", 2 }, { "Tres", 3 } };

        DataContext = this;   
    }

    public IDictionary<string, int> MyNumbers { get; set; }

    string _selectedNumber;
    public string SelectedNumber
    {
        get { return _selectedNumber; }
        set
        {
            _selectedNumber = value;
            Notify("SelectedNumber");
            UpdateMyNumberValue();
        }
    }

    int _myNumberValue;
    public int MyNumberValue
    {
        get { return _myNumberValue; }
        set 
        { 
            _myNumberValue = value;
            Notify("MyNumberValue");
        }
    }

    void UpdateMyNumberValue()
    {
        var key = SelectedNumber;
        if (key == null || !MyNumbers.ContainsKey(key)) return;

        new Thread(() =>
        {
            Thread.Sleep(3000);
            MyNumberValue = MyNumbers[key];
        }).Start();
    }

    public event PropertyChangedEventHandler PropertyChanged;
    void Notify(string property)
    {
        var handler = PropertyChanged;
        if(handler != null) handler(this, new PropertyChangedEventArgs(property));
    }
}

答案 1 :(得分:5)

您可以使用DispatcherFrame,这是一个示例转换器:

public class AsyncConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        object result = null;
        DoAsync(() =>
        {
            Thread.Sleep(2000); // Simulate long task
            result = (int)value * 2; // Some sample conversion
        });
        return result;
    }

    private void DoAsync(Action action)
    {
        var frame = new DispatcherFrame();
        new Thread((ThreadStart)(() =>
        {
            action();
            frame.Continue = false;
        })).Start();
        Dispatcher.PushFrame(frame);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

答案 2 :(得分:1)

在转换器中进行繁重的计算并不是一个好的设计 - 特别是如果你正在制作其他人应该使用的功能作为一个很好的例子。

我会使用你的ViewModel重写和使用MVVM作为类固醇的转换器,你可以用透明的方式完成所有这些事情 - 更容易编程,更容易理解的程序流,更容易理解代码。

然后你可以使用Prioritybindings:

http://msdn.microsoft.com/en-us/library/system.windows.data.prioritybinding.aspx

对于您的原始问题,我会在调用转换器时查看 - 如果绑定返回其值时,您可能无法让Async执行它的操作。我怀疑wpf等待属性返回然后调用转换器 - 在这种情况下,可能无法使转换器不能冻结gui。

您可以采取的方法:

  • 在您的转换器中,您应该开始提取数据并返回例如backgroundworker - 否则ui将冻结。
  • 在multibinding中传递对某事物的引用,所以当你的数据到达时你可以触发propertychanged

答案 3 :(得分:0)

我建议查看BackgroundWorker。它可以在后台线程上执行转换,然后在UI线程上引发已完成的事件。

请参阅http://www.dotnetperls.com/backgroundworker