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 ?

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.


Why not use task factory?

  var task = Task.Factory.StartNew(()=>{ /*do stuff*/ });

Task factory works the same way as Queue does but has the advantage of allowing you to handle any return information more elegantly

 var result = await task;

The Factory will only spawn threads when it makes sense to, so essentailly is the same as the thread pool

If you want to use schedule longer running tasks this is also considered the better option, in terms of recommended practices, but would need to specify that information on the creation of the task.

If you need further information on there is a good answer available here : ThreadPool.QueueUserWorkItem vs Task.Factory.StartNew


Need Your Help

Modifying a page by many users

web-services http java-ee web-applications web

In a web application, when 5 users are connected to it, and there is a part of the page that users can modify (for example the vote counter in stackoverflow). If a user make a vote_up, when will the

SSL certificate will encrypt the query string values used in my MVC 3 application

asp.net-mvc-3 ssl encryption

I want to encrypt the query string values used in my MVC3 application. If i implement SSL certificate, whether all the parameters passed with url in encrypted form or not. The application is already