Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actions in a single thread

My app does a lot of background tasks, and for each such action, I created a new thread for each action

Thread StreamResponse = new Thread(() => 
    {
        DB.ToDb(flag);
    });
StreamResponse.Start();

These actions take place thousands per minute. Noticed that the app starts eating RAM. That's normal, because the application creates thousands of threads and not closing them.

From here there is a question, how do I make it so that these actions were in a separate thread. For example, I create a thread in a separate class and in this thread commit acts.

Or otherwise can? The task that the thread was made and after the completion of the action is automatically closed. But perhaps more correctly just all these steps to do in another thread. What do you think? How to make?

May be using Dispatcher.BeginInvoke ?

like image 697
alexander Avatar asked Oct 29 '25 18:10

alexander


1 Answers

It seems that you could benefit from using the ThreadPool Class. From MSDN:

Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.

Here is a sample code for using it:

ThreadPool.QueueUserWorkItem((x) => 
{
    DB.ToDb(flag);
});

And you can set the maximum number of concurrent threads available in the thread pool using the ThreadPool.SetMaxThreads Method in order to improve performance and limit memory usage in your app.

like image 131
Thomas C. G. de Vilhena Avatar answered Oct 31 '25 08:10

Thomas C. G. de Vilhena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!