线程循环,直到进程正在运行



我的问题有点笼统,因为我仍在努力理解如何正确实现它,然而,鉴于我有以下代码:

class Class1
{
public static void Something()
{
if (a)
{
//do something in a;
if (b)
{
//do something in b;
if (c)
{
//do something in c;
if (d)
{
while (Process.GetProcessesByName("ProcessName").Length > 0)
{
//execute action
return;
}
if (Process.GetProcessesByName("ProcessName").Length <= 0)
{
//execute action when the ProcessName is closed
...
//start the loop from beginning
Something();
}
}
}
}
}
}
}

我想要实现的是:循环从Something((开始,直到它达到if(d(条件,然后我想在循环中运行某些操作,直到给定的进程名称正在运行,也许使用一个新的线程来提高性能(?(。一旦找不到进程名称,我想做一些其他操作,然后从头开始。这可能吗?

实现这一目标的最佳方式是什么?

不确定这是否正是你想要的。。。但这可能是一个良好的开端?

class Class1
{
private static bool a=true, b=true, c=true;
private static bool d()
{
Console.WriteLine("Launching Notepad");
Process P = Process.Start("notepad");
Console.WriteLine("Waiting for Notepad");
P.WaitForInputIdle();
Console.WriteLine("Notepad is ready!");
return true;
}
public static void Something()
{
while (true) // not sure how/when this exits
{
if (a)
{
//do something in a;
if (b)
{
//do something in b;
if (c)
{
//do something in c;
if (d())
{
// we'll assume after "d", the process has started
Process P = Process.GetProcessesByName("notepad").FirstOrDefault();
if (P != null)
{
P.EnableRaisingEvents = true;
P.Exited += (s, e) => {
//execute action when the ProcessName is closed
Console.WriteLine("Notepad closed.");
};
// execute action here?
Console.WriteLine("Action before loop.");
int counter = 1;
while (!P.HasExited)
{
// execute action or here?
Console.WriteLine("Waiting for Notepad to close: " + counter.ToString());
System.Threading.Thread.Sleep(1000); // check every second?
counter++;
}                                                                        
}
}
}
}
}
}

}
}

这是在WinForms应用程序中运行的吗?控制台应用程序?还有什么?。。。

最新更新