I have a process in a website (Asp.net 3.5 using Linq-to-Sql for data access) that needs to work as follows:
- Upload file
- Record and save info regarding file to database
- Import data from file into database
- Redirect to different page
When run sequentially like this, everything works fine. However, since the files being imported can be quite large, I would like step 3 to run on a different thread from the UI thread. The user should get to step 4 while step 3 is still in progress, and the screen on step 4 will periodically update to let the user know when the import is complete.
I am handling the threading as follows:
public class Import { public static void ImportPendingFile() { Import i = new Import(); Thread newThread = new Thread(new ThreadStart(i.ImportFile)); newThread.Start(); } public void ImportFile() { // 1. Query DB to identify pending file // 2. Open up and parse pending file // 3. Import all data from file into DB // 4. Update db to reflect that import completed successfully } }
And in the codebehind:
protected void butUpload(object sender, EventArgs e) { // Save file, prepare for import Import.ImportPendingFile(); Response.Redirect(NewLocation); }
When doing this, I am able to confirm via debugger that the new thread is starting up properly. However, whenever I do this, the thread aborts when trying to access the file (step 2 in the code behind). This works fine when run in the main thread, so something about the multi-threaded situation is preventing this. I had thought that since the file is saved to disk (which it is) that there shouldn’t be any problem with opening it up in a different thread. Any ideas where I have gone wrong and how I can fix it? Thanks!
Note: I am using a third-party assembly to open the file. Using reflector, I have found the following code related to how it opens up the file:
if (File.Exists(fileName)) { using (FileStream stream = new FileStream(fileName, FileMode.Open)) { // use stream to open file } }
Try Response.Redirect(url, false) , else the ‘Response’ will be ended just after that call.