Task management in .NET

In my application, I receive messages and event invoked. Event is defined in library, so I can only subscribe.

consumer.Received += (model, ea) => new Task(() =>
{
   var body = ea.Body;
   var message = Encoding.UTF8.GetString(body);
   Console.WriteLine(message);
}).Start();

I run new task when message received. But, it can be very big amount of messages and running task. I think, when I use new Task().Start() it will start straight away, so my system can get overloaded. The question is: how to manage tasks, without creating containers with fixed number of running tasks, because I want to use maximum of abilities and trust management to .NET. Thanks.

Upvotes: 1

Views: 1106

Answers (1)

usr
usr

Reputation: 171178

Here, the tasks are queued to the thread pool and executed based on its heuristics.

trust management to .NET

Yeah... the runtime has limited information about what task scheduling is optimal. Sometimes you need to take control. In particular, if you are doing IO. I have less experience with CPU limited workloads but they should be more OK with the default scheduling.

It is hard to recommend something concrete since it is unclear how representative the sample code is of your actual workload. If this is IO based you definitely should not rely on thread pool heuristics. The TPL has no idea what your IO devices can do.

Here, since you are not using async IO (in the sample code) you can use the TaskScheduler abstraction to create a task scheduler that has a limited degree of parallelism if you want to take control.

You're probably best off by testing a realistic workload. If you find that too many threads are being created you can limit the degree of parallelism to a sane value.

Upvotes: 1

Related Questions