1

I am reading Data from a serial port using the DataReceived event. While receiving data, I am making interpolations on the data and showing them in a PictureBox in real time. Everything works fine and I can see the interpolated heatmap data in the PictureBox great and quickly. But the problem is while data is being read, the WinForms application freezes, the form can't even apply the FormPaint event. The DataReceived event gets data, interpolates it, and applies this to the PictureBox. Suddenly the DataReceived event starts and gets data and moves on in the same cycle.

The DataReceived event -> the PictureBox refresh -> interpolate and draw on PictureBox.

Here is some code that might help you to understand the problem:

void seriPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{  
   ......  
   //I am getting data here
   .....  
   //then in order to see the data in picturebox in real time I use the following

   this.BeginInvoke((MethodInvoker)delegate { pictureBox1.Refresh();   });

}

Here is the PictureBox Paint event when refresh is triggered:

private void FrameBox_Paint(object sender, PaintEventArgs e)
{
    if (activeFrame != null)
    {
        DrawChart chart = new DrawChart();
        chart.ContourFrame(e.Graphics, activeFrame);
    }
}

Here is the contourFrame method:

//interpolation code above
for (int i = 0; i < npoints; i++)
{
    for (int j = 0; j < npoints; j++)
    {

       color = AddColor(pts[i, j], zmin, zmax);
       aBrush = new SolidBrush(color);
       points[0] = new PointF(pts[i, j].X, pts[i, j].Y);
       points[1] = new PointF(pts[i + 1, j].X, pts[i + 1, j].Y);
       points[2] = new PointF(pts[i + 1, j + 1].X, pts[i + 1, j + 1].Y);
       points[3] = new PointF(pts[i, j + 1].X, pts[i, j + 1].Y);
       g.FillPolygon(aBrush, points);
       aBrush.Dispose();
    }
}

I think the g.FillPolygon method takes more time than expected. Because when I comment in it, the form_paint event works too. But for the best results we can't sacrifice the data amount and quality. As I said, right now it gets the data, interpolates and draws quickly, but the only problem, is it locks all other functions in main thread I guess. This might be solved by threading but I am new on threads and a little confused. So I can't go further.

Any ideas how to move forward?

eddie_cat
  • 2,320
  • 3
  • 23
  • 40
smoothumut
  • 3,103
  • 1
  • 17
  • 30
  • 1
    This is a standard problem, a *fire-hose* issue. The UI thread simply can't keep up. You'll need to collect more data before you invoke. – Hans Passant Sep 05 '14 at 15:58

1 Answers1

0

I have changed the this.BeginInvoke to this this.invoke and now it doesnt freeze anymore. you can take a look at the difference between these two on this link What's the difference between Invoke() and BeginInvoke()

Community
  • 1
  • 1
smoothumut
  • 3,103
  • 1
  • 17
  • 30