后台工作者更新Gridview

时间:2019-02-23 05:03:20

标签: c# background backgroundworker

我想使用后台工作程序从表中更新datagridview。那可能吗 ?并且怀疑它是否会降低我的应用程序性能

1 个答案:

答案 0 :(得分:0)

可以。 这是一个在backgroundWorker完成后更新主UI线程中的DataGridView的示例。

    BackgroundWorker backgroundWorker;
    public MainWindow()
    {
        InitializeComponent();
        // initializing GridView with data 
        this.dataGrid.ItemsSource = new people[] {
            new people { Name = "John", LastName="Doe", Age = 40 } };
        // adding a button click handler
        this.btnAddPeople.Click += BtnAddPeople_Click;

        backgroundWorker = backgroundWorker ?? new BackgroundWorker();
        backgroundWorker.DoWork += BackgroundWorker_DoWork;
        backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
    }

    private void BtnAddPeople_Click(object sender, RoutedEventArgs e)
    {
        backgroundWorker.RunWorkerAsync();
    }

    private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        var newList = this.dataGrid.ItemsSource.Cast<people>().Union(
                new[] {
                    new people { Name = "Asher", LastName = "Richard", Age = 26 },
                    new people { Name = "Joyce", LastName = "Herrera", Age = 37 }
                }
            );            
        this.dataGrid.ItemsSource = newList;
    }

    private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {            
        Thread.Sleep(1000);            
    }

    class people
    {
        public string Name { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }