2013-02-13 113 views
0

我无法找到我正在寻找的答案,但如果是这样,请将其链接,然后我将关闭此重复帖子。新程序不按顺序?

作为一个程序我工作的一部分,我想三个简单的事情在这个顺序发生:

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!

+1

如果你正在运行在单个线程(UI线程),那么UI将不会更新,直到你回来之后一切。您尚未显示足够的代码来确认这是否属实,但您与UI元素进行交互(看起来像)的事实使其极其可能。 – 2013-02-13 21:06:32

+1

当您在必须绘制条的相同线程上运行代码时,您不会看到进度条动画。当你扔进一个消息框,允许处理绘画事件时,会产生混淆。您的方法存在根本上的缺陷,在单独的工作线程中运行昂贵的代码,以至于无法停止UI线程。 BackgroundWorker始终是一个不错的选择。 – 2013-02-13 21:07:09

+0

我不熟悉BackgroundWorker类,我将如何构建第2步以运行它? – user1959800 2013-02-13 21:12:06

回答

1

进度条不会显示,因为您正在将它绘制在逻辑所在的同一个线程中。你将不得不在另一个线程中执行此操作。最简单的方法是使用一个BackgroundWorker的

这将帮助你:http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

+0

我试过thread.Sleep(500),甚至thread.sleep(2000),并没有什么区别。 – user1959800 2013-02-13 21:10:44

+2

那是因为你的睡眠导致UI线程进入睡眠状态。 BackgroundWorker在单独的线程中运行,允许UI线程跟踪消息。 – GalacticCowboy 2013-02-13 21:15:00

+0

银河是对的!编辑我的回答 – bpoiss 2013-02-13 21:15:40