Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh canvas

I am trying to create a visual representation of any sorting algorithm where the data is represented in an int[] array. An example of bubble sort on wikipedia:

Bubble sort from wikipedia

My sorting algorithms all raise an event ItemsSwapped when two items in the int[] array are swapped. I am trying to display the data after every event on canvas, this is my code:

// Handler for ItemsSwapped event.
private void Render(object sender, ItemsSwapEventArgs e)
{
    canvas.Children.Clear();
    int numberOfElements = e.Data.Length;

    for (int x = 0; x < numberOfElements; x++)
    {
        RenderValue(x, e.Data[x]);
    }
    // Here I should somehow refresh canvas.
}

private void RenderValue(int x, int y)
{
    var value = new Ellipse
                    {
                        Width = 5,
                        Height = 5,
                        Stroke = Brushes.Black,
                        StrokeThickness = 2,
                    };
    Canvas.SetTop(value, x);
    Canvas.SetLeft(value, y);
    canvas.Children.Add(value);
}

The problem is, that the canvas doesn't refresh itself, it just displays the final solution after some time. How can I refresh it after every raised event?

Edit - I tried with UpdateLayout, InvalidateMeasure and Dispatcher object, but neither worked.

like image 507
sventevit Avatar asked Mar 24 '13 20:03

sventevit


1 Answers

Maybe you start your sort algorithm on the UI thread, so it won't update until finished. Try sorting in another thread and update the Canvas children using the Dispatcher, by calling Invoke or BeginInvoke.

If your ItemsSwapped handler is called from a separate thread, it may look like this:

private void Render(object sender, ItemsSwapEventArgs e)
{
    Dispatcher.Invoke((Action)(() =>
        {
            canvas.Children.Clear();
            int numberOfElements = e.Data.Length;

            for (int x = 0; x < numberOfElements; x++)
            {
                RenderValue(x, e.Data[x]);
            }
        }));
}
like image 107
Vladimir Avatar answered Oct 05 '22 23:10

Vladimir