Skip to main content
 首页 » 编程设计

c#之进程退出时尝试运行代码 C#

2024年02月05日17jirigala

我的 C# 程序运行一个进程,该进程在单击特定按钮时启动命令提示符应用程序并向其传递参数。

  1. 程序从用户选择中获取目录路径,并检查它是否为空。

  2. 如果它不为空,for each 循环将遍历目录中每个文件的完整路径数组。 它还会将进度条设置为 0 并准备好递增

  3. 当它循环时,它将使用 Process 运行 cli-task

问题来了: 完成文件循环任务后,我希望它删除文件并增加进度条。

如果像这样一个一个地进行,这会工作得很好:

process.WaitForExit(10000); 
File.Delete(fileName); 
progressBar1.Increment(1); 

但是这个程序非常慢。因为它会等待每个进程完成,然后再开始下一个进程。

然后我尝试了下面的代码:

string[] files = Directory.GetFiles(label1.Text); 
 
if (files.Length != 0) 
{ 
    progressBar1.Value = 0; 
    progressBar1.Minimum = 0; 
    progressBar1.Maximum = files.Length; 
 
    foreach (string fileName in files) 
    { 
        System.Diagnostics.Process process = new System.Diagnostics.Process(); 
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 
        //startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
        startInfo.FileName = @"C:\Program Files\cli-tool\cli.exe"; 
        startInfo.Arguments = "-i " + "\"" + fileName + "\"" + " -o " + "\"" + label2.Text + "\\" + Path.GetFileName(fileName) + "\"" + " -s -t"; 
        process.StartInfo = startInfo; 
        process.EnableRaisingEvents = true; 
        process.Start(); 
        process.Exited += delegate 
        { 
            File.Delete(fileName); 
            progressBar1.Increment(1); 
        }; 
    } 

不幸的是,当我以这种方式运行它时,程序会在到达 File.Delete(fileName) 部分时崩溃,但原始的 process.start 任务有效,但它能够删除退出它的第一个进程的第一个文件。

visual studio的调试控制台显示如下错误:

A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll The program '[3308] IonicFolderProtector.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

我无法确定这段代码有什么问题。 我是否错误地认为 process.Exited += delegate {//some code }; 将作为同时创建的每个进程每次运行?

请您参考如下方法:

很确定您正在运行 variable capture issue ,将 var temp = filename; 放在 foreach 中,然后在委托(delegate)中执行 File.Delete(temp);。

foreach (string fileName in files) 
{ 
    var temp = fileName; 
    System.Diagnostics.Process process = new System.Diagnostics.Process(); 
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 
    //startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
    startInfo.FileName = @"C:\Program Files\cli-tool\cli.exe"; 
    startInfo.Arguments = "-i " + "\"" + fileName + "\"" + " -o " + "\"" + label2.Text + "\\" + Path.GetFileName(fileName) + "\"" + " -s -t"; 
    process.StartInfo = startInfo; 
    process.EnableRaisingEvents = true; 
    process.Start(); 
    process.Exited += delegate 
    { 
        File.Delete(temp); 
        progressBar1.Increment(1); 
    }; 
} 

这将确保实际删除的是正确的文件。您可能还需要调用 progressBar1.Increment(),因为我不知道该事件是否会在 UI 线程上运行。

    process.Exited += delegate 
    { 
        File.Delete(temp); 
        progressBar1.Invoke(new Action(() => progressBar1.Increment(1))); 
    };