简体   繁体   English

暂停C#中的主要流程

[英]Suspending main process in C#

I am developing an application in C#. 我正在用C#开发应用程序。 As part of an error condition, I would like to bring up a file in Notepad for the user to edit (while pausing the main process). 作为错误情况的一部分,我想在记事本中调出一个文件供用户编辑(在暂停主要过程的同时)。 I am able to bring the file up using Process.Start. 我可以使用Process.Start调出文件。 What I can't figure out is how to pause the main application until the user saves or quits out of the notepad file. 我不知道的是如何在用户保存或退出记事本文件之前暂停主应用程序。 Is there something other than Process.start that I could use that would launch the Notepad.exe in the main process or some other trick I can use. 除了Process.start之外,还有其他我可以使用的东西,它可以在主进程中启动Notepad.exe或我可以使用的其他技巧。 I feel like there is an easy solution to it that I am overlooking. 我觉得有一个简单的解决方案可供我忽略。 Thanks in advance. 提前致谢。

You could use Process.WaitForExit to block the main program until Notepad is closed. 您可以使用Process.WaitForExit阻止主程序,直到关闭记事本。

Making it block until the file is saved or closed would be a bit trickier. 将其阻止直到文件被保存或关闭将比较棘手。

One option here would be to have a ManualResetEvent, and wait on it. 这里的一种选择是拥有一个ManualResetEvent,然后等待它。 You could then listen for Process.Exited (after setting Process.EnableRaisingEvents ), and use this to call Set() on the wait handle. 然后,您可以侦听Process.Exited (在设置Process.EnableRaisingEvents之后 ),并使用它在等待句柄上调用Set()。 This would handle allowing your code to continue when the process exits. 这将使您的代码在流程退出时继续运行。

For handling the file being saved, a separate FileSystemWatcher could watch for the save (file change) on the file itself. 为了处理要保存的文件,一个单独的FileSystemWatcher可以监视文件本身的保存(文件更改)。 If the file saves/changes, you could continue on by calling Set(). 如果文件保存/更改,则可以通过调用Set()继续。

I believe you should be able to do something like this. 我相信您应该可以做这样的事情。

var notePad = new Process { StartInfo = { FileName = "notepad.exe", Arguments = "newfile.txt" } };
        notePad.Start();

        while(!notePad.HasExited)
        {

        }

        MessageBox.Show("Done.");

The "Done." “完成”。 message box shouldn't show up until you close notepad. 关闭记事本之前,消息框不会显示。 Then again, the answer above mine is less hackish. 再说一次,我上面的答案没有那么强硬。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM