Are background threads a bad idea? Why?
Posted
by Matt Grande
on Stack Overflow
See other posts from Stack Overflow
or by Matt Grande
Published on 2010-05-19T20:55:43Z
Indexed on
2010/05/19
21:00 UTC
Read the original article
Hit count: 200
So I've been told what I'm doing here is wrong, but I'm not sure why.
I have a webpage that imports a CSV file with document numbers to perform an expensive operation on. I've put the expensive operation into a background thread to prevent it from 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 & messages for users thrown in)
So my three-fold question is: a) Is this a bad idea? b) Why is this a bad idea? c) What would you do instead?
© Stack Overflow or respective owner