繁体   English   中英

Observable 集合异步更新

[英]Observable collection async update

许多人建议使用调度程序更新 UI 线程上的 observablecollection。 但我想做这样的事情。 使用这个实现我可以面对什么邪恶? 我不想使用调度程序,因为它会在多线程中造成死锁。

namespace WpfApplication162
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new Data();
    }
}
public class Data:INotifyPropertyChanged
{
    private ObservableCollection<string> nameList;
    public ObservableCollection<string> NameList 
    { 
        get
        {
            return this.nameList;
        }
        set
        {
            this.nameList = value;
            this.RaisePropertyChaged("NameList");
        }
    }

    public ObservableCollection<string> TempList { get; set; }
    public Data()
    {
        NameList = new ObservableCollection<string>();
        NameList.Add("Loading");
        Action Start = new Action(UpdateAysnc);
        IAsyncResult result = Start.BeginInvoke(new AsyncCallback(SetList), null);
    }
    public void SetList(object param)
    {
        NameList = TempList;
    }
    public void UpdateAysnc()
    {
        TempList = new ObservableCollection<string>();
        System.Threading.Thread.Sleep(10000);
        for (int i=0;i<10;i++)
        {
            TempList.Add(i.ToString());
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChaged(string info)
    {
        if (PropertyChanged!= null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}
}

xml

    <Grid>
    <ListView ItemsSource="{Binding NameList}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding .}"></Label>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

尝试这个:

public Data()
        {
            NameList = new ObservableCollection<string>();
            NameList.Add("Loading");

            UpdateAysnc(results => SetList(results));

        }
        public void SetList(object param)
        {
            NameList = TempList;
        }
        public void UpdateAysnc(Action<ObservableCollection<string>> onUpdateComplete)
        {
            var tempList = new ObservableCollection<string>();
            System.Threading.Thread.Sleep(10000);
            for (int i=0;i<10;i++)
            {
                tempList.Add(i.ToString());
            }

            onUpdateComplete(tempList);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM