0

mycode :

        Canvas myCanvas = new Canvas();
>       Rectangle myRectangle = new Rectangle();

>                  Task.Factory.StartNew(() =>
>                  {
>                         while(true)
>                          {
>                             myCanvas.Children.Clear();
>                            //do something
>                            for(int i=1;i<=100;i++)
>                            {
>                               myCanvas.Children.Add(myRectangle[i]);
>                            }
                           }
>                  }).ContinueWith(t =>
>                  {
> 
>                  }, System.Threading.CancellationToken.None, TaskContinuationOptions.None,
>                  TaskScheduler.FromCurrentSynchronizationContext());

I still got error : "Specified Visual is already a child of another Visual or the root of a CompositionTarget." what i should do?

1 Answers1

1

You might want to use Dispatcher.Invoke method.

while (true)
{
     Dispatcher.Invoke(new Action(() => { myCanvas.Children.Clear(); }));
     for (int i = 1; i <= 100; i++)
     {
         Dispatcher.Invoke(new Action(() => { myCanvas.Children.Add(myRectangle[i]); }));
     }
}

Note that Invoke blocks the calling thread.

Ron
  • 3,127
  • 1
  • 11
  • 26
  • It's work!! Thank you very much. excuse me can you explain to me what different invoke and begininvoke ? – Kittinun Pongsukjai Feb 05 '17 at 22:39
  • When you use Invoke, the calling thread waits for completion. This is not true for BeginInvoke. See [this link](http://stackoverflow.com/questions/229554/whats-the-difference-between-invoke-and-begininvoke) or google it for other explanations. – Ron Feb 05 '17 at 22:50