C# serialport dataReceived事件和线程问题导致在C中冻结表单#

C# serialport dataReceived事件和线程问题导致在C中冻结表单#,c#,multithreading,drawing,C#,Multithreading,Drawing,我正在使用DataReceived事件从串行端口读取数据。在接收数据时,我对数据进行插值,并将其实时显示在一个PictureBox中。一切正常,我可以在PictureBox中快速看到插值的热图数据。但问题是,当读取数据时,WinForms应用程序冻结,表单甚至无法应用FormPaint事件。DataReceived事件获取数据,对其进行插值,并将其应用于PictureBox。突然,DataReceived事件开始并获取数据,并在同一周期内继续 DataReceivedevent->Picture

我正在使用
DataReceived
事件从串行端口读取数据。在接收数据时,我对数据进行插值,并将其实时显示在一个PictureBox中。一切正常,我可以在PictureBox中快速看到插值的热图数据。但问题是,当读取数据时,WinForms应用程序冻结,表单甚至无法应用
FormPaint
事件。
DataReceived
事件获取数据,对其进行插值,并将其应用于PictureBox。突然,
DataReceived
事件开始并获取数据,并在同一周期内继续

DataReceived
event->
PictureBox
refresh->interpolate and draw on
PictureBox

以下是一些可能有助于您理解问题的代码:

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();   });

}
以下是触发刷新时的PictureBox绘制事件:

private void FrameBox_Paint(object sender, PaintEventArgs e)
{
    if (activeFrame != null)
    {
        DrawChart chart = new DrawChart();
        chart.ContourFrame(e.Graphics, activeFrame);
    }
}
以下是contourFrame方法:

//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();
    }
}
//上面的插值代码
对于(int i=0;i
我认为
g.FillPolygon
方法比预期花费更多的时间。因为当我在其中发表评论时,form_paint事件也起作用。但为了获得最佳结果,我们不能牺牲数据量和质量。正如我所说,现在它获取数据、插值和绘制速度很快,但唯一的问题是,它锁定了主线程中的所有其他函数。这可以通过线程来解决,但我对线程还不熟悉,有点困惑。所以我不能再进一步了


有什么想法吗?

我已将this.BeginInvoke更改为this.invoke,现在它不再冻结。您可以在此链接上查看这两者之间的区别

这是一个标准问题,一个消防水带问题。UI线程根本跟不上。在调用之前,需要收集更多数据。