0

Hi i have a program i created for my website i was trying to update it so that the intense part of the code would run in a separate thread. The new thread creates several costume controls that i need to be placed inside of a container as a child control on the main GUI thread, but every time i run the code i get this error "The calling thread cannot access this object because a different thread owns it". The debugger after throwing this error highlights the code part under [ if (FileStack.Dispatcher.CheckAccess()) ] Every time i run the code and the program attempts to invoke the control. Here is my code

 public delegate void ADDFiLEHandel(FileControlxaml File);


 public void ADDFiles(FileControlxaml File)
      {

          if (FileStack.Dispatcher.CheckAccess())
          {
              FileStack.Children.Add(File);  //this is the code that gets height-lighted by the debugger 
          }
          else
          {
                      FileStack.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new ADDFiLEHandel(ADDFiles), File);

          }

Then i call the invoke like such from the new thread which i had to set the thread state to STA, What am i doing wrong Ive spent hours trying to get this to work.

    public void createfilethread(object data)
    {
    FileControlxaml  NewFile = new FileControlxaml();
    NewFile.Title = "Hellow World";
    ADDFiles(NewFile);
    }

1 Answers1

1

You cannot do this. When you instantiate DispatcherObjects in a thread that does not have an associated Dispatcher, a new dispatcher is created and associated to that thread. You cannot mix different UIElements created in different threads.

Why would you create UIElements in a second thread? that's what the "UI Thread" is meant for.

Rethink your approach.

Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154