Async process start and wait for it to finish

后端 未结 5 1085
小鲜肉
小鲜肉 2020-11-27 15:31

I am new to the thread model in .net. What would you use to:

  1. start a process that handles a file (process.StartInfo.FileName = fileName;)
  2. wait for th
5条回答
  •  遥遥无期
    2020-11-27 16:12

    "and waiting must be async" - I'm not trying to be funny, but isn't that a contradiction in terms? However, since you are starting a Process, the Exited event may help:

    ProcessStartInfo startInfo = null;
    Process process = Process.Start(startInfo);
    process.EnableRaisingEvents = true;
    process.Exited += delegate {/* clean up*/};
    

    If you want to actually wait (timeout etc), then:

    if(process.WaitForExit(timeout)) {
        // user exited
    } else {
        // timeout (perhaps process.Kill();)
    } 
    

    For waiting async, perhaps just use a different thread?

    ThreadPool.QueueUserWorkItem(delegate {
        Process process = Process.Start(startInfo);
        if(process.WaitForExit(timeout)) {
            // user exited
        } else {
            // timeout
        }
    });
    

提交回复
热议问题