我在這裏有一點困惑。爲什麼方法在沒有中斷的情況下返回true,而在中斷時返回false? C#
背景:我有一個應用程序記錄用戶選擇要顯示哪些文件後查看的文件。
不過,我也有自己選擇,直到他們關閉他們正在查看的文件指出,仍然隱藏文件之後一個WinForm出現。
下面是相關代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
namespace ViewTracker
{
public partial class NewFile : Form
{
//checks to see if a file is open
public NewFile()
{
InitializeComponent();
//
OpenDocuments();
//starts the timer component
tm_CountDown.Start();
while (CheckFileIsOpen() == false)
{
this.Hide();
}
this.Show();
}
//timer to count down
//executes every 1 second, interval of the timer component
private void tm_CountDown_Tick(object sender, EventArgs e)
{
}
#endregion
#region METHODS AND EVENTS
//opens documents based on file selection
private void OpenDocuments()
{
}
//SHUT DOWN EVERYTHING (files at least)
private void CloseEverything()
{
}
//checks to see if a file is open and when the file closes shows the new file select dialog
private bool CheckFileIsOpen()
{
Process[] pr_excel = Process.GetProcessesByName("EXCEL");
Process[] pr_word = Process.GetProcessesByName("WINWORD");
Process[] pr_pdf = Process.GetProcessesByName("ACROBAT");
if (pr_excel.Count() != 0)
{
while (pr_excel[0].HasExited == false)
{
return false;
}
}
else if (pr_word.Count() != 0)
{
while (pr_word[0].HasExited == false)
{
return false;
}
}
else if (pr_pdf.Count() != 0)
{
while (pr_pdf[0].HasExited == false) ;
{
return false;
}
}
else if (prisonImages.Visible == true)
{
while (prisonImages.Visible == true)
{
return false;
}
}
return true;
}
}
}
的問題出現在while (CheckFileIsOpen() == false)
。如果我在Visual Studio中放了一個break,然後逐步完成,程序按預期運行(表單保持隱藏狀態,直到進程結束)。但是,如果我沒有中斷運行,看起來好像該進程從未運行。
我試過Thread.Sleep(1000)
在while (CheckFileIsOpen() == false)
聲明之前,看看是否可能只是停止線程幾秒鐘可能會讓它有機會讓進程打開,但是整個應用程序只能無限期地凍結。
的問題: 是我的應用程序只是反應也快趕上的過程和他們打開之前解僱?如果是這樣,我可以使用哪些選項來避免直接跳到假定沒有進程打開?
謝謝你的時間。
編輯:
我結束了這張貼後尋找解決辦法幾分鐘。 我改變了一些執行步驟,最後使用Process.WaitForExit()
方法來滿足我的要求。
如果你想知道,這裏是如何CheckFileIsOpen()
作品現在:
private void CheckFileIsOpen()
{
Process[] pr_excel = Process.GetProcessesByName("EXCEL");
Process[] pr_word = Process.GetProcessesByName("WINWORD");
Process[] pr_pdf = Process.GetProcessesByName("ACROBAT");
if (pr_excel.Count() != 0)
{
pr_excel[0].WaitForExit();
}
else if (pr_word.Count() != 0)
{
pr_word[0].WaitForExit();
}
else if (pr_pdf.Count() != 0)
{
pr_pdf[0].WaitForExit();
}
}
只有你'while'的一個循環中'CheckFileIsOpen()'可以循環多次,這是一個具有欺騙性的小';'在同一行的末尾。 –
爲什麼在忙等待(while循環)時執行此操作?更好的方法是偶爾使用定時器和檢查狀態。 –
而不是使用定時器或while循環,只需在「Form」對象中有事件。從所有者應用程序中訂閱這些事件,然後在其處理程序中響應這些事件。 https://msdn.microsoft.com/zh-cn/library/ms229603(v=vs.110).aspx(請參閱事件驅動的驗證部分) – Snoopy