How to delay my print function so I can see when each object is being printed

In my program, I have an array of objects and I want to print each object one at a time with a delay.

This is my Draw () function now:

    public void Draw()
    {
        myCanvas.Children.Clear();
        foreach (Square Sq in MyDrawings)
        {
            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                sq.Draw();
            }));
        }
    }

      

My sq.draw () function is currently drawing a rectangle and adding it to the canvas:

             rect = new Rectangle
             {
                 Stroke = Brushes.Black,
                 StrokeThickness = 0.5,
                 Fill = Brushes.Black,
                 Height = Width,
                 Width = Width
             };
             Canvas.SetTop(rect, x * Width);
             Canvas.SetLeft(rect, y * Width);
             Form.myCanvas.Children.Add(rect);

      

I tried adding Thread.Sleep (); in the main Draw () function, but it seems to block the UI thread and when it unblocks the entire array has been drawn.

I also tried to use DispatcherTimer, but I don't know what delay to add as I want to print every object, not based on time.

Fixed code:

    public void Draw()
    {
        myCanvas.Children.Clear();
        foreach (Square Sq in MyDrawings)
        {
            Task.Run(() =>
            {
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    sq.Draw();
                }));
                Thread.Sleep(100);
            });
        }
    }

      

+3


source to share


1 answer


If you just want to iterate over and collect asynchronous / parallel execution of print jobs one by one, you can do something like

    foreach (Square Sq in MyDrawings)
    {
        Task.Run(() =>
        {
            sq.Draw();
            Thread.Sleep(SOME_MILLISECONDS_TO_WAIT);
        }));
    }

      



This will pause the iteration over the number of SOME_MILLISECONDS_TO_WAIT

ms specified and jump to another item in the collection. Naturally, if you are worried about feedback from Task

or want to control the launch of the task as much as possible, you will need to add this code as well.

0


source







All Articles