alexander
alexander

Reputation: 195

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 ?

Upvotes: 4

Views: 674

Answers (2)

konkked
konkked

Reputation: 3231

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

Upvotes: 0

Thomas C. G. de Vilhena
Thomas C. G. de Vilhena

Reputation: 14585

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.

Upvotes: 4

Related Questions