简体   繁体   中英

How to wait for a task to finish

I've got a Windows Form, where I've got a report being exported to PDF format.

After the report is generated, I would like to have the application terminated completely. I have added an Application.Exit() clause, however this sometimes closes the process while exporting is still happening.

Hence, I would like to close the application only if the exporting is complete.

I have tried the following:

   while(true) 
   {
    if (Process.GetCurrentProcess().WaitForInputIdle())
    {
        Application.Exit();
    }
   }

and also:

while(true) 
{
    if (Process.GetCurrentProcess().Responding)
    {
        Application.Exit();
    }
}

None have worked however - the application still sometimes closes before the export is complete.

What am I doing wrong?

You could start exporting in another process and wait for it to finish (check out the related post: Wait till a process ends ).

If you don't want that, you can check whether the file to which the exporting is done exists and whether it is locked (check out Wait Until File Is Completely Written ).

The problem is that if the application is designed to be responsive to user interactions, both ways will close the application even though it is still working.

Maybe you should monitor the output of the application? That is: If the PDF file is present, the process is done. Or rather: If the PDF file is present and hasn't been modified for 15 seconds or something, exit the application.

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