When does Asp.net end the background thread?

I was working on a project and there is most of the email sending part of it and when the user clicks on the button he gets "Thank you emails were sent" immediately as a response and the same method also starts an asynchronous thread.

ThreadPool.QueueUserWorkItem(SendEMail, _message);

      

This thread is queued when the user clicks the submit button, but since this is the default Background Thread

I was expecting for the response to the page to finish, this thread would complete, but it did not, because the current thread that starts this thread was also Background Thread

a Worker Thread

so it means there is an unfinished foreground thread (maybe MainThread or Worker Threads) still alive, but I don't know when they finish because their end time will affect my background worker threads; When the last foreground thread ends, it causes the process to terminate as well as background threads.

Should I be afraid of this, or Asp.NET can handle it automatically and I'm a little confused because I read a lot about it and now things are confused.

Could you please clarify the situation a little?

Thanks in advance.

0


source to share


3 answers


Using ThreadPool for long running tasks will negatively impact the performance of your application (since ASP.NET also uses ThreadPool to handle incoming requests).

Creating threads manually for each task can also become a problem if too many threads are created.



One technique that I have used in the past is to create a custom ThreadPool when the application starts and set tasks to that ThreadPool. A simple custom ThreadPool can consist of a single thread and a task queue.

+3


source


When you call QueueUserWorkItem, a new thread will be drawn from the thread pool if available, and execute a callback function on that thread. If no threads are available, the function blocks until the thread is freed. Once it finishes executing the method, the thread will be suspended and returned to the pool for further reuse. Your only problem is that pooled threads are also used to serve requests, so if you run long-running tasks on them you could compromise all system request serving capabilities as there is a limited number of threads in the pool and if they are all busy performing long-term operations. Future HTTP requests will be queued. Alternatively, you can consider creating threads manually:new Thread(state => { }).Start();



+1


source


You can use MSMQ to create your email queue and have one thread handling the queue.

The following post might be helpful as it suits your problem area. While it doesn't use MSMQ, it is a good post when handling scheduled tasks using ASP.net.

Simulate a Windows service using ASP.NET to run scheduled jobs

+1


source







All Articles