修改线程时遇到问题

时间:2012-12-26 17:55:30

标签: c# .net multithreading visual-studio-2010 treeview

  

可能重复:
  Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on
  Cross-thread operation not valid

这是我的方法:(我已经看到了其他几个与线程相关的答案,但我不理解这些解决方案如何适合我的特定情况。)

private void live_refresh()
{
    while (true)
    {
            viewBackup.Nodes.Clear();
            Control.storage.refresh_files_list();
            viewBackup.Nodes.Add(Control.storage.get_files_node());

            List<FileInfo> list = Control.sched.get_difference();
            this.viewCopy.Items.Clear();
            foreach (FileInfo file in list)
                this.viewCopy.Items.Add(file.FullName.Substring(Control.filer.get_path().Length + 1));
        }
    }
}

抛出异常:“跨线程操作无效:控制'viewBackup'从其创建的线程以外的线程访问。”

any1可以帮我解决这个问题吗?有什么方法除了Invoke()?我不明白..

1 个答案:

答案 0 :(得分:2)

使用Invoke从非UI线程更新UI。要确定UI线程,请使用InvokeRequired

// Invoke version of your code sample:

private void live_refresh()
{
  if(viewBackup.InvokeRequired)
  {
    viewBackup.Invoke(new MethodInvoker(live_refresh));
    return ;
  }
  while(true)
  ....
  .....
}