[英]Adding data read from the socket to DataGridView (in c#)
我使用 C# 创建了一个套接字侦听器。 我想立即在 DataGridWiew 中列出在此套接字上读取的数据。 (通过此套接字每秒传输大约 100 个数据)我成功读取了套接字上的数据,但是在尝试立即将其列在 DataGridView 上时,屏幕冻结,直到数据流停止。 当数据流停止时,所有数据都列在 DataGridView 上。 但相反,我希望 DataGridView 在添加数据时连续成功刷新。
有没有办法立即在 DataGridView 中成功列出这么多数据?
我在哪里犯错?
编码:
frm.loggGridView.ColumnCount = 5;
frm.loggGridView.ColumnHeadersVisible = true;
DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();
columnHeaderStyle.BackColor = Color.Beige;
columnHeaderStyle.Font = new Font("Verdana", 10, FontStyle.Bold);
frm.loggGridView.ColumnHeadersDefaultCellStyle = columnHeaderStyle;
frm.loggGridView.Columns[0].Name = "ID";
frm.loggGridView.Columns[1].Name = "LATITUDE";
frm.loggGridView.Columns[2].Name = "LONGITUDE";
frm.loggGridView.Columns[3].Name = "ALTITUDE";
frm.loggGridView.Columns[4].Name = "TIME";
int i= 0;
try
{
PointF p1;
while (true)
{
byte[] bytes = listener.Receive(ref groupEP);
String FlightData = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
// Console.WriteLine("broadcast veri {0} :\n {1}\n", groupEP.ToString(), FlightData);
String[] FlightDataSplit = FlightData.Split(' ', '\n');
p1 = new PointF(FlightDataSplit[1], FlightDataSplit[0], FlightDataSplit[2]);
frm.loggGridView.Rows.Add();
frm.loggGridView.Rows[i].Cells[0].Value = i;
frm.loggGridView.Rows[i].Cells[1].Value = p1.latitude;
frm.loggGridView.Rows[i].Cells[2].Value = p1.longitude;
frm.loggGridView.Rows[i].Cells[3].Value = p1.altitude;
frm.loggGridView.Rows[i].Cells[4].Value = DateTime.Now;
i++;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
我试图模拟一个快速的 LINQPad 示例。 这将在后台继续添加新结果,而不会冻结应用程序
// Simple GridView control
DataGridView gridView = new System.Windows.Forms.DataGridView();
gridView.Columns.Add("A", "A");
gridView.Columns.Add("B", "B");
gridView.Columns.Add("C", "C");
// Display the Control in LINQPad
PanelManager.DisplayControl(gridView);
await Task.Run(async () =>
{
while(true)
{
// your listener code
var results = Enumerable.Range(0, 100).Select(x => x).ToList();
if(gridView.IsHandleCreated)
{
// render on the UI thread
gridView.Invoke((MethodInvoker)delegate
{
for (int i = 0; i < results.Count; i++)
{
int index = gridView.Rows.Add();
gridView.Rows[index].Cells[0].Value = 1;
gridView.Rows[index].Cells[1].Value = 2;
gridView.Rows[index].Cells[2].Value = 3;
}
});
}
await Task.Delay(1000); // remove this from your solution, your listener is blocking
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.