Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run lengthy tasks from an ASP.NET page?

I've got an ASP.NET page with a simple form. The user fills out the form with some details, uploads a document, and some processing of the file then needs to happens on the server side.

My question is - what's the best approach to handling the server side processing of the files? The processing involves calling an exe. Should I use seperate threads for this?

Ideally I want the user to submit the form without the web page just hanging there while the processing takes place.

I've tried this code but my task never runs on the server:

Action<object> action = (object obj) =>
{
      // Create a .xdu file for this job
       string xduFile = launcher.CreateSingleJobBatchFile(LanguagePair, SourceFileLocation);

      // Launch the job                 
      launcher.ProcessJob(xduFile);
};

Task job = new Task(action, "test");
job.Start();

Any suggestions are appreciated.

like image 463
Jimmy Collins Avatar asked Jan 21 '23 10:01

Jimmy Collins


2 Answers

You could invoke the processing functionality asynchronously in a classic fire and forget fashion:

In .NET 4.0 you should do this using the new Task Parallel Library:

Task.Factory.StartNew(() =>
{
    // Do work
});

If you need to pass an argument to the action delegate you could do it like this:

Action<object> task = args =>
{
    // Do work with args
};    
Task.Factory.StartNew(task, "SomeArgument");

In .NET 3.5 and earlier you would instead do it this way:

ThreadPool.QueueUserWorkItem(args =>
{
   // Do work
});

Related resources:

  • Task Class
  • ThreadPool.QueueUserWorkItem Method
like image 86
Enrico Campidoglio Avatar answered Jan 23 '23 00:01

Enrico Campidoglio


Use:

ThreadPool.QueueUserWorkItem(o => MyFunc(arg0, arg1, ...));

Where MyFunc() does the server-side processing in the background after the user submits the page;

like image 28
mellamokb Avatar answered Jan 23 '23 01:01

mellamokb