I have some trouble with updating of Canvas`s content using Parallel.Foreach or IEnumerable.AsParallel().ForAll() or Threads.
I have a lot of Lines in Canvas, and i need to change their coordinates relatievly to the new size of Canvas in which they are, when user resizes the window.
I Put my Lines in
IEnumerable<Line> lineCollection = canvas.Children.OfType<Line>();
Then i trying to loop them parallel using Parallel.Foreach or IEnumerable.AsParallel().ForAll()
I recieve an AggregateException in that cases. It says, that the calling thread cannot access this object because the main thread owns it.
How can I do that with my UIElements.
This is my code:
private void canvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
Double hDelta = e.NewSize.Height / e.PreviousSize.Height;
if (Double.IsInfinity(hDelta)) return;
IEnumerable<Line> LineCollection = canvas.Children.OfType<Line>();
try
{
Parallel.ForEach(LineCollection, (line) =>
{
Double topProp = (Double)line.GetValue(Canvas.TopProperty) * hDelta;
line.SetValue(Canvas.TopProperty, topProp);
});
}
catch (AggregateException ae)
{
ae.Handle((x) =>
{
if (x is Exception)
{
MessageBox.Show(x.ToString(), "error");
}
return false;
});
}
}
I recieve an Error at this line:
line.SetValue(Canvas.TopProperty, topProp);