0

Possible Duplicate:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on
Cross-thread operation not valid

This is my method: (I have seen several other cross thread-related answers but am not understanding how those solution fit my particular case.)

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

throws exception: "Cross-thread operation not valid: Control 'viewBackup' accessed from a thread other than the thread it was created on."

can any1 help me solve this problem ? is there any way except the Invoke() ? i don't understand it..

Community
  • 1
  • 1
nadav
  • 552
  • 5
  • 11

1 Answers1

2

Use Invoke to update UI from non UI thread. To determine UI Thread, use InvokeRequired

// Invoke version of your code sample:

private void live_refresh()
{
  if(viewBackup.InvokeRequired)
  {
    viewBackup.Invoke(new MethodInvoker(live_refresh));
    return ;
  }
  while(true)
  ....
  .....
}
Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
Tilak
  • 30,108
  • 19
  • 83
  • 131
  • I'm down-voting because this is one of the most duplicated questions on SO: http://stackoverflow.com/questions/5037470 – Paul Sasik Dec 26 '12 at 18:03
  • updated answer with example – Tilak Dec 26 '12 at 18:03
  • @Tilak: That is better, but you are still adding to the duplication issue. At 4550 rep you know better. You know that this has been asked too often and the right thing to do here is close the question as a duplicate instead of trying to earn more rep. – Paul Sasik Dec 26 '12 at 18:05
  • he is helping. i didnt get to understand to other answers given. and right now i dont get the exception but the function is running not like a thread. my program is stuck – nadav Dec 26 '12 at 18:13
  • ohh, with multithreading, things become slightly more complex. You need to check for synchronization issue as well. More code is needed to check further – Tilak Dec 26 '12 at 18:18