Actions in one thread

There are many background tasks in my application and for each such activity I created a new thread for each activity

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

      

These actions take place thousands per minute. I noticed that the application starts eating RAM. This is ok because the application creates thousands of threads and does not close them.

This raises the question, how can I make it so that these actions are in a separate thread. For example, I create a thread in a separate class and on that thread the commit is acting.

Or otherwise? The task created by the thread is automatically closed after the action is completed. But, perhaps, it is more correct to do all these steps in a different thread. What do you think? How to do it?

Can it be used Dispatcher.BeginInvoke

?

+3


source to share


2 answers


It seems you could take advantage of the ThreadPool Class . From MSDN:

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

Here's some sample code to use it:



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

      

And you can set the maximum number of parallel threads available in the thread pool with the ThreadPool.SetMaxThreads Method to improve performance and limit memory usage in your application.

+3


source


Why not use a factory task?

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

      

The factory task works the same as in Queue, but has the advantage of allowing you to handle any returned information more elegantly

 var result = await task;

      



factory will only generate threads when it makes sense, so essentailly is the same as thread pool

If you want to use a schedule for longer tasks, this is also considered the best option in terms of recommended practices, but you will need to provide this information about creating the task.

If you need more information there is a good answer found here: ThreadPool.QueueUserWorkItem vs Task.Factory.StartNew

0


source







All Articles