简体   繁体   中英

Launch process from Threadpool worker thread (and wait if needed)

I have an application that processes file transfers. In some instances, I need to launch some pre/post processing executables that do stuff with the files.

So the order of events (in brief) would be like this:

  1. Worker thread is created
  2. Worker realizes it needs to launch a pre-process executable before starting the transfer Pre-process is launched, worker waits... if it waits too long, the transfer will not occur and the thread should finish gracefully
  3. File is transferred
  4. Worker realizes it needs to launch a post-process executable after the transfer is finished
  5. Post-process is launched, worker doesn't care to wait

Basically, I don't care how long the post process executable runs after the transfer has occurred. Therefore, should I anticipate any problems if I launch the process from a thread that is then returned to the pool?


//Post process

        Process process = null;
        ProcessStartInfo psi = new ProcessStartInfo(executable, args);
        psi.UseShellExecute = true;

        try
        {
            process = Process.Start(psi);
            //The pre-process simply calls Process.WaitForExit(timeout value)
            launched = true;
        }
        catch (InvalidOperationException) { }
        catch (ArgumentException) { }
        catch (System.ComponentModel.Win32Exception) { }
        catch (System.IO.FileNotFoundException) { }

There is nothing wrong with that at all.

Think about it:

  • Returning a thread to the threadpool doesn't actually mean anything - the thread is still there.
  • Processes are not in any way dependent on their parent threads or processes - it's possible for a process to spawn a child process and then exit.

That's very dangerous. If you use up all of your thread pool threads on long-running tasks then other things that need them will stop working. You can even dead-lock your whole application.

The rule is simple:

  • Short and fast: Thread Pool Thread
  • Long and slow: Manually created thread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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