我無法找到我正在尋找的答案,但如果是這樣,請將其鏈接,然後我將關閉此重複帖子。新程序不按順序?
作爲一個程序我工作的一部分,我想三個簡單的事情在這個順序發生:
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