I've a scheduled task in my ASP.NET MVC site that nightly sends notifications for the users.
I've been sending and awaiting notifications one by one, but it's taking an hour to complete now, so I thought I should send them in batches.
int counter = 0;
List<Task> tasks = new List<Task>();
foreach (var user in users)
{
tasks.Add(Task.Run(async () =>
{
await user.SendNotificationAsync();
counter++;
}));
if (tasks.Count >= 20)
{
await Task.WhenAll(tasks);
tasks.Clear();
}
}
if(tasks.Any())
{
await Task.WhenAll(tasks);
tasks.Clear();
}
But I've read that creating multiple threads is not efficient on the servers. How should I run multiple instances of the method on the server?