Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using Only One ForEach Loop

Please see the following Code:-

 Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
           Parallel.ForEach(Segments.OfType(Of Segment),
                             Sub(segment)
                                 Try
                                      segment.DrawLine(e.Graphics)
                                 Catch ex As Exception
                                 End Try
                             End Sub
                             )
        
          Parallel.ForEach(Ellipses.OfType(Of Ellipse),
                             Sub(ellipse)
                                 Try
                                      ellipse.DrawEllipse(e.Graphics)
                                 Catch ex As Exception
                                 End Try
                             End Sub
                             )
      End Sub

Is it Possible to use only One ForEach loop instead of Two as shown above? If No, is there a way to Enhance the Speed of Execution by using async and await?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It would be possible to use only one loop if all types of shapes would be in the same collection. To enable this, you would need to have an abstract base class for shapes.

Public MustInherit Class Shape
    Public Property ForeColor As Color

    ... other common properties

    Public MustOverride Draw(g As Graphics)
End Class

Then you can derive the concrete shapes like this (with Line as an example):

Public Class Line
    Inherits Shape

    Public Property StartPoint As PointF
    Public Property EndPoint As PointF

    Public Overrides Sub Draw(g As Graphics)
        Using pen As New SolidPen(ForeColor)
            g.DrawLine(pen, StartPoint, EndPoint)
        End Using
    End Sub
End Class

The you can add all the kind of shapes to a List(Of Shape) and loop it like this

Parallel.ForEach(Shapes,
    Sub(shape)
        shape.Draw(e.Graphics)
    End Sub
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading