Search code examples
c#web-scrapingtimeout

how to set a timeout for download in C#


I am writing an application that downloads web contents.The problem is, when download starts, the whole app freezes until it download is completed. Is there a way to set a timeout which stops the process after sometime?


Solution

  • If you don't want the whole program to freeze, then you can complete the download on a BackgroundWorker, but if you simply want to run a process for a given amount of time and then stop it, you can use Process.WaitForExit, and set the timeout to 2 minutes.

    After 2 minutes, if it returns false, then you can use Process.Kill to terminate it.

    Process process = Process.Start("myDownloadApp.exe");
    
    //wait 2 minutes
    if (!process.WaitForExit(120000))
    {
        process.Kill();
    }