【问题标题】:the calling thread cannot access this object because a different thread owns it in wpf [closed]调用线程无法访问此对象,因为另一个线程在 wpf 中拥有它 [关闭]
【发布时间】:2012-01-20 11:38:48
【问题描述】:
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
}

【问题讨论】:

  • 似乎很容易解释?您无法访问数据网格,因为它是在另一个线程上创建的。
  • Possible duplicate。此外,为了将来在发布问题时参考,介绍和描述您的问题会很有帮助,而不仅仅是发布您的代码。如果问题足够明显,您可以仅从代码帖子中理解问题,那么如果您搜索您的问题(例如通过GoogleStackOverflow),那么您很可能会找到解决方案。
  • 您可以使用后台工作组件的 ProgressChanged 事件,而不是使用计时器并在经过时调用 UpdateChatContent,该事件还允许更新 UI 控件..
  • 那我如何将 myvar 分配给 datagrid1'itemsSource 你能解释一下它是如何完成的

标签: c# wpf multithreading user-interface


【解决方案1】:

要访问 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);
    }
}

【讨论】:

  • 我需要从数据库中重复获取数据
  • 此代码不会阻止您这样做。
猜你喜欢
  • 2011-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-13
相关资源
最近更新 更多