我在这里有一点困惑。为什么方法在没有中断的情况下返回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