0

Is there any way to download a file from URL to server in the background? When a form is submitted, the file uploading processed automatically in the background, so user doesn't need to wait for the file upload.

In Windows Application, there is BackgroundWorker class. but how about ASP.NET?

Seehyung Lee
  • 590
  • 1
  • 15
  • 32
  • 1
    You should not do that; IIS can unload ASP.Net AppDomains at any time. Use a separate process. – SLaks Aug 21 '13 at 13:33
  • I think this thread should give a good summary of the problem and its solution(s) http://stackoverflow.com/q/12319642/1236044 – jbl Aug 21 '13 at 14:20
  • background threads are problematic on asp.net. On Azure you can use web jobs. See http://curah.microsoft.com/52143/using-the-webjobs-feature-of-windows-azure-web-sites – RickAndMSFT May 06 '14 at 23:35

1 Answers1

2

This is not the sort of thing that you want to run on the Response thread, since it will delay the response to the user until the file can be download and processed. It is more well-suited for a different thread running as a service on the computer (or an Azure Worker Role) that will perform these items for you.

However, if you really want (or have to) run it through IIS/ASP.net, and if you don't care about returning anything to the user, you can run all of your logic in a different thread or through a delegate invoked asynchronously. See this answer (quoting from there) for a sample on running the delegate asynchronously.

private delegate void DoStuff(); //delegate for the action

protected void Button1_Click(object sender, EventArgs e)
{
    //create the delegate
    DoStuff myAction = new DoStuff(DownloadStuff); 

    //invoke it asynchronously, control passes to next statement
    myAction.BeginInvoke(null, null);
}

private void DownloadStuff() { 
  // your functionality here - this can also go in a code library
}

See MSDN for more info on how to work with delegates (including using parameters to pass info).

Community
  • 1
  • 1
Yaakov Ellis
  • 40,752
  • 27
  • 129
  • 174
  • 1
    Also as a reminder, none of the context instances will be available, so a reference to those objects or their property values would need to be passed in with the thread start parameters. This includes HttpContext.Current, and on that, the Session, Request, Response, Application, etc. – ps2goat Aug 21 '13 at 14:27