I have this simple code in aspnet :assuming no exceptions nor file locking nor process terminates :
new Thread(()=>{
Thread.sleep(15000);
// GC.Collect();
File.Write (...); // dummy file
}).Start();
// GC.Collect();
From my tests , the file is always created.
Question
The scenario which is not understood to me is that the request lifetime is much shorter than thread execution and still it works . Thats all . Thats my main question
Is it always guaranteed that the file will be created ?
Nb it’s just a test to examine behavior .
Also the page is an empty page with only this code. Also i know that join will wait
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
It is not. When IIS decides to recyle the entire process it will take down both background and foreground threads. See this answer.
Luckily, you can make sure they are not interrupted. You can tell ASP.NET about your thread by implementing the IRegisteredObject interface. You can then register your object using HostingEnvironment.RegisterObject. See The Dangers of Implementing Recurring Background Tasks In ASP.NET
Method 2
Unless the thread is aborted or the above statements throw exceptions, yes, it will always be created (leaving file permissions and IO problems out of the picture).
Reasons the thread might be aborted:
- (Manual) application pool recycle;
- Request abandoned;
- Crash of application.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0