简体   繁体   English

如何等待操作完成?

[英]How to Wait Until an Operation Finishes?

I have C# code which included Python code in which it is run through CMD codes in C#.我有 C# 代码,其中包括通过 C# 中的 CMD 代码运行的 Python 代码。 When the Python code is run the operations are done, a JSON file is created and then it will be opened in C#.当 Python 代码运行完成时,会创建一个 JSON 文件,然后将在 C# 中打开它。 In this situation, how the C# code can wait to check if the output of Python ( data.json ) is created or not, and just when the output is created, the rest of C# code is allowed to be run:在这种情况下,C# 代码如何等待检查 Python 的输出( data.json )是否已创建,并且仅在创建输出时,才允许运行其余的 C# 代码:

Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
process.StandardInput.WriteLine("F:\\");
process.StandardInput.WriteLine("cd F:\\Path");
process.StandardInput.WriteLine("python Python_Code.py");


process.StandardInput.Flush();
process.StandardInput.Close();
process.WaitForExit();

Then, the generated data with Python will be retrieved:然后,将检索使用 Python 生成的数据:

string Output_Python = File.ReadAllText(@"Data.json");
JavaScriptSerializer Ser = new JavaScriptSerializer();
Predicted Output = Ser.Deserialize<Predicted>(Output_Python);

You don't need to go through cmd.exe.您不需要通过 cmd.exe。 The Python interpreter itself is an executable; Python 解释器本身是一个可执行文件; in other words, it can be started and executed directly.换句话说,它可以直接启动和执行。 The arguments for the Python interpreter (like the path+name of the script to be executed) and desired working directory can be set through the appropriate Process.StartInfo properties :可以通过适当的Process.StartInfo 属性设置 Python 解释器的参数(如要执行的脚本的路径+名称)和所需的工作目录:

Process process = new Process();
process.StartInfo.FileName = "python.exe";
process.StartInfo.Arguments = "Python_Code.py";
process.StartInfo.WorkingDirectory = @"F:\Path";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();

Now you only need to wait for the Python interpreter to exit (which means it finished executing the python script)现在你只需要等待 Python 解释器退出(这意味着它完成了 Python 脚本的执行)

process.WaitForExit();

and after the Python process has exited, simply check if the json file exist/has been written:在 Python 进程退出后,只需检查 json 文件是否存在/已写入:

if (System.IO.File.Exists(pathToJsonFile))
{
    ... do stuff with json file ...
}
else
{
    ... json file does not exist, something went wrong...
}

Side note: I kept process.StartInfo.RedirectStandardOutput = true;旁注:我保留了process.StartInfo.RedirectStandardOutput = true; in my code example here, since i don't know what your program will really do.在我这里的代码示例中,因为我不知道你的程序会真正做什么。 However, unless your program wants to process the output of the script that normally appears in a console window, setting RedirectStandardOutput to true is not necessary.但是,除非您的程序想要处理通常出现在控制台窗口中的脚本的输出,否则没有必要将RedirectStandardOutput设置为true

You should have a look at the FileSystemWatcher class.您应该查看FileSystemWatcher类。 Documentation here .文档在这里

Then you can do something like this:然后你可以做这样的事情:

using (FileSystemWatcher watcher = new FileSystemWatcher())
{
    watcher.Path = YourDirectory;
    // Watch for changes in LastWrite time
    watcher.NotifyFilter = NotifyFilters.LastWrite;

    // Watch for the wanted file
    watcher.Filter = "data.json";

    // Add event handlers.
    watcher.Created += WhateverYouWantToDo;
}

You can check to see if the file data.json is finished being written to its output folder (Code from this answer ):您可以检查文件data.json是否已完成写入其输出文件夹( 此答案中的代码):

private bool IsFileLocked(FileInfo file) 
{ 
   FileStream stream = null; 
   try 
  { 
    stream = file.Open(FileMode.Open,    FileAccess.ReadWrite, FileShare.None); 
  } 
  catch (IOException)
  { 
//the file is unavailable because it is: 
//still being written to 
//or being processed by another thread 
//or does not exist (has already been processed) 
    return true; 
  }
  finally 
  { 
    if (stream != null) stream.Close(); 
  } 
//file is not locked return 
return false; 
}

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

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