【发布时间】:2014-12-12 23:41:40
【问题描述】:
我已经有了这个,但它不起作用...我需要检查来自 plc 的位是否高。如果它仍然很高,我需要等待 5 秒并再次检查。现在我正在尝试寻找一些东西,以便为用户提供一些视觉反馈。在文本框中,我想输入“等待...”,而等待后的分数每 5 秒增加一次。我尝试了很多东西,但似乎无法让它发挥作用。大多数情况下它只是挂起 25 秒而不更新 GUI,然后它继续......:/
// First check if the plc bit, that says if there is still an order active,
// is still set. If so then we wait a couple seconds.
var bitorder = Main.PIOGetValue(jbmis.IO_GET_INPUT, "BoxManInStarted");
int counter = 1;
string loadingpoints = "";
loadtimer.Tick += timer_Tick;
loadtimer.Interval = (int)TimeSpan.FromSeconds(5).TotalMilliseconds;
loadtimer.Start();
loadtimer.Enabled = true;
// Stopwatch sw = new Stopwatch();
while(bitorder != 0 && loadtimercounter != 25)
{
// TODO multithreaded
#region testcode
// MessageBox.Show("Waiting for previous order to be stopped" + loadingpoints);
// Context.UserMessageService
// .ShowMessage("Waiting for previous order to be stopped" +
// loadingpoints, "Waitingfororder");
// sw.Start();
// while (sw.Elapsed < TimeSpan.FromSeconds(25))
// {
// if (sw.Elapsed.Seconds % 5 == 0)
// {
// loadingpoints = loadingpoints + ".";
// tbScannedEANPick.Background = Brushes.OrangeRed;
// tbScannedEANPick.Text = "Waiting" + loadingpoints;
// }
// }
// sw.Stop();
// loadingpoints = loadingpoints + ".";
// tbScannedEANPick.Background = Brushes.OrangeRed;
// tbScannedEANPick.Text = "Waiting" + loadingpoints;
// tbScannedEANPick.UpdateLayout();
#endregion
if (loadtimercounter % 5 == 0)
{
loadingpoints = loadingpoints + ".";
tbScannedEANPick.Background = Brushes.OrangeRed;
tbScannedEANPick.Text = "Waiting" + loadingpoints;
tbScannedEANPick.IsReadOnly = true;
bitorder = Main.PIOGetValue(jbmis.IO_GET_INPUT, "BoxManInStarted");
}
counter ++;
}
// After 25 seconds stop timer and continue
loadtimer.Stop();
void timer_Tick(object sender, EventArgs e)
{
loadtimercounter += 5;
}
我找了半天……我试过用Thread.sleep、定时器、秒表……都在主线程或侧线程中……
提前致谢!!
【问题讨论】:
-
Timer和Thread.Sleep(StopWatch是吗?)只要您在 UI 线程本身中执行 长时间运行的作业,就不会工作。您可以尝试拆分作业并将小部分作业放入计时器(switch/case步骤)。或者,您可以使用Task、Thread和BackgroundWorker在 UI 线程中简单地不完成这项长期工作。