我正在尝试从数据库中选择值并从那里不断更新图表。使用如何从 C# 中的另一个线程更新 GUI?我的代码是:
private void button1_Click(object sender, EventArgs e)
{
string myConnection = "datasource=localhost;port=3306;username=root;password=root";
MySqlConnection conDataBase = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand(" select * from data.test; ", conDataBase);
MySqlDataReader myReader;
this.Invoke((MethodInvoker)delegate
{
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
this.chart1.Series["Series1"].Points.AddXY(myReader.GetString("datetime"), myReader.GetInt32("temp"));
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
});
}
虽然我没有收到任何错误,但我不认为它的工作作为图表是恒定/静态的。有什么建议么。我基本上想要的是该图表根据数据库中的新值不断更新……类似于心跳监视器或类似的效果。
任何建议...问候
编辑:我也尝试使用后台工作人员,但在按钮单击时我也得到以下信息:
Cross thread operation not valid: Control 'charTemperature' accessed from athread other than the thread it was created on
编码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Threading;
namespace project
{
public partial class Form2 : Form
{
private BackgroundWorker bw = new BackgroundWorker();
public Form2()
{
InitializeComponent();
bw.WorkerSupportsCancellation = true;
bw.WorkerReportsProgress = false;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnTemperature_Click(object sender, EventArgs e)
{
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
//this.Invoke((MethodInvoker)delegate
// {
/* string myConnection = "datasource=localhost;port=3306;username=root;password=root";
MySqlConnection conDataBase = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand(" select * from data.test; ", conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
this.chartTemperature.Series["Temperature"].Points.AddXY(myReader.GetString("datetime"), myReader.GetInt32("temp"));
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
//});*/
}
private void btnStopUpdating_Click(object sender, EventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
string myConnection = "datasource=localhost;port=3306;username=root;password=root";
MySqlConnection conDataBase = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand(" select * from data.test; ", conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
this.chartTemperature.Series["Temperature"].Points.AddXY(myReader.GetString("datetime"), myReader.GetInt32("temp"));
System.Threading.Thread.Sleep(1000);
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}
又一次徒劳的尝试……点击按钮没有任何反应……
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Threading;
namespace project
{
public partial class Form2 : Form
{
private BackgroundWorker bw = new BackgroundWorker();
public string vdatetime;
public Int32 vtemp;
public Form2()
{
InitializeComponent();
bw.WorkerSupportsCancellation = true;
// bw.WorkerReportsProgress = false;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnTemperature_Click(object sender, EventArgs e)
{
//if (bw.IsBusy != true)
//{
this.bw.RunWorkerAsync();
//}
//this.Invoke((MethodInvoker)delegate
// {
/* string myConnection = "datasource=localhost;port=3306;username=root;password=root";
MySqlConnection conDataBase = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand(" select * from data.test; ", conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
this.chartTemperature.Series["Temperature"].Points.AddXY(myReader.GetString("datetime"), myReader.GetInt32("temp"));
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
//});*/
}
private void btnStopUpdating_Click(object sender, EventArgs e)
{
// if (bw.WorkerSupportsCancellation == true)
//{
this.bw.CancelAsync();
//}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
//break;
}
else
{
string myConnection = "datasource=localhost;port=3306;username=root;password=root";
MySqlConnection conDataBase = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand(" select * from data.test; ", conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
//this.Invoke((MethodInvoker)delegate
//{
while (myReader.Read())
{
vdatetime = myReader.GetString("datetime");
vtemp = myReader.GetInt32("temp");
//Thread.Sleep(300);
// this.chartTemperature.Series["Temperature"].Points.AddXY(myReader.GetString("datetime"), myReader.GetInt32("temp"));
// System.Threading.Thread.Sleep(1000);
}
conDataBase.Close();
// });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// The user canceled the operation.
MessageBox.Show("Operation was canceled");
}
else if (e.Error != null)
{
// There was an error during the operation.
string msg = String.Format("An error occurred: {0}", e.Error.Message);
MessageBox.Show(msg);
}
else
{
this.chartTemperature.Series["Temperature"].Points.AddXY(vdatetime, vtemp);
}
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}