所以我研究了beginInvoke从另一个线程调用一个方法。 (如果我错了,请纠正我)
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
this.BeginInvoke((Action)(() =>
{
red_light1 = comport.message(4, 8, 32);
if (red_light1 == "1")
{
ellipse1.FillEllipse(red_on, 250, 133, 24, 24);
}
else
{
ellipse1.FillEllipse(red_off, 250, 133, 24, 24);
}));
Thread.Sleep(300);
}
}
}
}
但是我想在这个“动作”中读取另外5个值,我不知道如何调用它。
如何实现一个方法,在我的代码中调用6个变量,然后调用它。
method implementation
{
//no parameters & no return value, just read and store the values in variables like "red_light1" and after color some ellipses depending on values (1|0).
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
this.BeginInvoke( **method call** );
Thread.Sleep(300);
}
}
答案 0 :(得分:1)
你正在做的事情毫无意义。
你似乎正在使用BackgroundWorker
,它通常用于执行繁重的操作(在从ThreadPool获得的后台线程上),然后你在后台线程上没有做任何重的事情
事实上,你根本没有做任何事情:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// a loop that never exits !!!!
// no break, no cancel, nothing!!!
while (true)
{
// here is the Background thread
//... and absolutely NOTHING happens here...
// the code that follows gets invoked on the UI thread
// (which defeats the purpose of the BackgroundWorker...)
// then immediately returns (because it's asynchronous)
// to be invoked again
// and again, and again...
// (Is your app unresponsive perhaps? doesn't it hang?)
this.BeginInvoke((Action)(() =>
{
red_light1 = comport.message(4, 8, 32);
if (red_light1 == "1")
{
ellipse1.FillEllipse(red_on, 250, 133, 24, 24);
}
else
{
ellipse1.FillEllipse(red_off, 250, 133, 24, 24);
}));
// Your UI hangs here !!!
// (Because you're putting your UI thread to sleep!)
// At least call Thread.Sleep() in the background thread.
// Or call synchronous Invoke() instead of asynchronous BeginInvoke()
// so your background thread waits untill the operation on UI thread
// is completed before trying to perform it again
Thread.Sleep(300);
}
}
}
}