Async process start and wait for it to finish

后端 未结 5 1127
小鲜肉
小鲜肉 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:34

    Adding an advanced alternative to this old question. If you want to wait for a process to exit without blocking any thread and still support timeouts, try the following:

        public static Task WaitForExitAsync(this Process process, TimeSpan timeout)
        {
            ManualResetEvent processWaitObject = new ManualResetEvent(false);
            processWaitObject.SafeWaitHandle = new SafeWaitHandle(process.Handle, false);
    
            TaskCompletionSource tcs = new TaskCompletionSource();
    
            RegisteredWaitHandle registeredProcessWaitHandle = null;
            registeredProcessWaitHandle = ThreadPool.RegisterWaitForSingleObject(
                processWaitObject,
                delegate(object state, bool timedOut)
                {
                    if (!timedOut)
                    {
                        registeredProcessWaitHandle.Unregister(null);
                    }
    
                    processWaitObject.Dispose();
                    tcs.SetResult(!timedOut);
                },
                null /* state */,
                timeout,
                true /* executeOnlyOnce */);
    
            return tcs.Task;
        }
    

    Again, the advantage to this approach compared to the accepted answer is that you're not blocking any threads, which reduces the overhead of your app.

提交回复
热议问题