我无法找到我正在寻找的答案,但如果是这样,请将其链接,然后我将关闭此重复帖子。新程序不按顺序?
作为一个程序我工作的一部分,我想三个简单的事情在这个顺序发生:
1)显示选取框进度条 2)通过CMD并移动在运行某些命令输出到一个可访问的字符串 3.)停止/隐藏进度条
我看到的问题是,我的代码没有按顺序执行,我为什么超级困惑。它似乎去步骤2-1-3,这是不应该的。
为了让事情变得更加奇怪,如果我在步骤1和步骤2之间取消注释消息框,则按顺序执行。
是否有新的CMD程序将这个问题抛出怪物?
这里是我这个方法的代码:
//STEP 1 - Updates label and starts progress bar
lblSelectDiagnostic.Text = "Diagnostic Running";
progressBarDiag.Visible = true;
progressBarDiag.MarqueeAnimationSpeed = 100;
//MessageBox.Show("Status Updated");
//STEP 2 - Runs "Test Internet Connection"
//Gets selected diagnostic name
string strSelectedDiag = listBoxDiagnostics.SelectedItem.ToString();
var name = strSelectedDiag.Substring(strSelectedDiag.LastIndexOf(':') + 1);
strSelectedDiag = name.Trim();
if (strSelectedDiag.Contains("Test Internet Connection"))
{
//Pings Google
ProcessStartInfo info = new ProcessStartInfo();
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.FileName = "cmd.exe";
info.CreateNoWindow = true;
//Creates new process
Process proc = new Process();
proc.StartInfo = info;
proc.Start();
//Writes commands
using (StreamWriter writer = proc.StandardInput)
{
if (writer.BaseStream.CanWrite)
{
writer.WriteLine("ping www.google.com");
writer.WriteLine("exit");
}
writer.Close();
}
string PingGoogle = proc.StandardOutput.ReadToEnd();
proc.Close();
}
//STEP 3 - Resets label and stops progress bar
progressBarDiag.MarqueeAnimationSpeed = 0;
progressBarDiag.Visible = false;
lblSelectDiagnostic.Text = "Select Diagnostic to Run:";
-Thanks!
如果你正在运行在单个线程(UI线程),那么UI将不会更新,直到你回来之后一切。您尚未显示足够的代码来确认这是否属实,但您与UI元素进行交互(看起来像)的事实使其极其可能。 – 2013-02-13 21:06:32
当您在必须绘制条的相同线程上运行代码时,您不会看到进度条动画。当你扔进一个消息框,允许处理绘画事件时,会产生混淆。您的方法存在根本上的缺陷,在单独的工作线程中运行昂贵的代码,以至于无法停止UI线程。 BackgroundWorker始终是一个不错的选择。 – 2013-02-13 21:07:09
我不熟悉BackgroundWorker类,我将如何构建第2步以运行它? – user1959800 2013-02-13 21:12:06