调用线程无法访问此对象,因为wpf中有另一个线程拥有它

本文关键字:线程 wpf 拥有 因为 另一个 访问 对象 调用 | 更新日期: 2023-09-27 18:20:49

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中有另一个线程拥有它

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

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);
    }
}