BeginInvoke разъяснения
Поэтому я изучил, что 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);
}
}
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);
}
}
}
}