因此,我有這個從Arduino獲取值(6個變量)的C#應用程序。最初我使用了一個計時器,每100ms調用一次讀取函數,但它會掛起我的用戶界面,並且響應有點沉重。我想使用一個連續讀取這些變量的背景工作。我將這些讀取的調用放在DoWork方法中,並將值放入C#中的變量中,並將它們分配到標籤中。但它不起作用。 (對不起,我的英語)C# - backgroundworker通過串行從Arduino連續獲取數據
namespace testtemp
{
public partial class tempreaderform : Form
{
public tempreaderform()
{
InitializeComponent();
}
communicator comport = new communicator();
Boolean portConnection = false;
String red_light1;
private void button1_Click(object sender, EventArgs e)
{
if (comport.connect(57600, "I'M ARDUINO", 4, 8, 16))
{
label1.Text = "Connection Successful - Connected to "+comport.port;
portConnection = true;
backgroundWorker1.RunWorkerAsync(); // I am not sure if here I should start the backgroundworker.
}
else
{
label1.Text = "Not connected . . . ";
portConnection = false;
}
}
private void groupBox1_Paint(object sender, PaintEventArgs e)
{
Graphics ellipse1 = groupBox1.CreateGraphics();
Brush red_on = new SolidBrush(Color.Red);
Brush red_off = new SolidBrush(Color.DarkRed);
label2.Text = "Red : " + red_light1; //Here is a label which I want to show "1" if "red_light1" is "1" and "0" if "red_light1" is "0"
if (red_light1 == "1") ellipse1.FillEllipse(red_on, 250, 133, 24, 24);
else ellipse1.FillEllipse(red_off, 250, 133, 24, 24); // Here is what I really want to do (the label.Text part was only to see the value) I want to color a ellipse depending on "red_light1" value.
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
red_light1 = comport.message(4, 8, 32);
}
}
}
}
}
注:我的DoWork方法tryied這個「label1.Text = red_light1」,但它說,我不能在另一個線程創建的變量給值,這樣的事情。
你把backgroundWorker1_DoWork在另一個線程裏面E類功能? – Thealon
我不確定我是否理解你。我第一次做這個。我相信我在DoWork方法中添加的代碼會在另一個線程中自動「工作」。 – user3672802
那麼這個while循環將永遠不會結束,因此它將永遠停留在那裏。請看看這裏:https://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx。 – Thealon