C # Block code before processing a process descriptor in files

I have a foreach loop that starts a process in try / catch. In the final section of my try / catch /, finally, I try to ensure that the process does not have a descriptor for any files. I need to delete files that were being processed.

Nothing I tried seems to work. I keep getting System.IO exceptions. "This file is currently being used by another process."

You can see at the end when I use WaitForExit () before returning from this method. The very next method call is deleting files. Why then will the process still be open or have a handle in any of these files?

Thank!

try
{
   foreach (var fileInfo in jsFiles)
   {
     //removed for clarity
     _process.StartInfo.FileName = "\"C:\\Program Files\\Java\\jre6\\bin\\java\"";
     _process.StartInfo.Arguments = stringBuilder.ToString();
     _process.StartInfo.UseShellExecute = false;
     _process.StartInfo.RedirectStandardOutput = true;
     _process.Start();
   }
 }
 catch (Exception e)
 {
   BuildMessageEventArgs args = new BuildMessageEventArgs("Compression Error: " + e.Message,
                                string.Empty, "JSMin", MessageImportance.High);
   BuildEngine.LogMessageEvent(args);

 }
 finally
 {
   _process.WaitForExit();
   _process.Close();
 }
+3
4

, . , foreach . , WaitForExit Close finally .

, / . , fileInfo . , .

+2

- . , .

, foreach try?

, , .

+3

?

For the GUI application, you will need to execute Process.CloseMainWindow.

0
source
foreach (var fileInfo in jsFiles)
{
    using (Process process = new Process())
    {
        try
        {
            //Other stuff
            process.Start();
        }
        catch (...)
        {
            //Exception Handling goes here...
        }
        finally
        {
            try
            {
                process.WaitForExit();
            }
            catch (...)
            {
            }
        }
    }
}
  • Process.WaitForExit() may throw an exception, so it needs a / catch attempt.
  • If you create a process in an instruction using, you do not need to worry about closing it; .NET will dispose of it correctly.
  • It is usually best not to precede local variables with an underscore. Most people just use this for their fields.
0
source

Source: https://habr.com/ru/post/1775858/


All Articles