本文介绍了调用线程无法访问此对象,因为在 wpf 中另一个线程拥有它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
}

private void btnAddGroup_Click(object sender, RoutedEventArgs e)
{
    if (bw.IsBusy != true)
    {
        bw.RunWorkerAsync();
    }
}

System.Timers.Timer timer = null;

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    timer = new System.Timers.Timer();
    timer.Interval = 1000;
    timer.Enabled = true;
    timer.Elapsed += new ElapsedEventHandler(UpdateChatContent);
}

public void UpdateChatContent()
{
    var myVar=(from a in db  select a).tolist();
    datagrid1.itemsSource=myVar;//here is the exception occurs
}

推荐答案

要访问 WPF 中的 UI 元素,您必须在 UI 线程上进行访问.如果您像这样更改代码,它应该可以工作:

For accessing UI elements in WPF you have to do the accessing on the UI Thread.It should work if you change the code like this:

public void UpdateChatContent()
{
    var myVar=(from a in db select a).Tolist();
    OnUIThread(() => datagrid1.ItemsSource=myVar);
}

private void OnUIThread(Action action)
{
    if(Dispatcher.CheckAccess())
    {
        action();
    }
    else
    {
        // if you don't want to block the current thread while action is
        // executed, you can also call Dispatcher.BeginInvoke(action);
        Dispatcher.Invoke(action);
    }
}

这篇关于调用线程无法访问此对象,因为在 wpf 中另一个线程拥有它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 08:38