Are background threads bad ideas? What for?

So they told me what I'm doing wrong here, but I'm not sure why.

I have a web page that imports a CSV file with document numbers for an expensive operation. I put an expensive operation in the background thread to prevent it blocking the application. Here's what I have in a nutshell.

protected void ButtonUpload_Click(object sender, EventArgs e) { if (FileUploadCSV.HasFile) { string fileText; using (var sr = new StreamReader(FileUploadCSV.FileContent)) { fileText = sr.ReadToEnd(); } var documentNumbers = fileText.Split(new[] {',', '\n', '\r'}, StringSplitOptions.RemoveEmptyEntries); ThreadStart threadStart = () => AnotherClass.ExpensiveOperation(documentNumbers); var thread = new Thread(threadStart) {IsBackground = true}; thread.Start(); } } 

(obviously with some error checking and messages for users)

So my three dimensional question:

  • a) Is this a bad idea?
  • b) Why is this a bad idea?
  • c) What would you do instead?
+7
multithreading c # background
source share
3 answers

A possible problem is that the background thread is running in your website application pool. IIS may decide to recycle your application pool, resulting in an expensive operation being killed before it is completed.

I would prefer the option where I had a separate process, perhaps a Windows service that would receive expensive execution requests and execute them outside the asp.net process. This would not only mean that your expensive operation would be saved when you restart the application pool, but it will also simplify your web application, since it should not process processing.

Saying that a service can perform an expensive process using some kind of interprocess communication, the service can poll the database table or file, or you can use the management queue that the service will listen to.

There are many ways to do this, but I want to say that you should separate the expensive process from your web application, if possible.

+8
source share

I recommend using the BackgroundWorker class instead of using threads directly. This is due to the fact that BackgroundWorker designed specifically for performing background operations for a graphical application and, among other things, provides mechanisms for sending updates to the user interface.

+7
source share

a: yes.

Use ThreadPool;) Queue a WorkItem - avoids the overhead of creating a ton of threads.

+1
source share

All Articles