I have a program that generates txt files with randomized contents. Many documents have to be generated, so I use Tasks to get the work done faster. I want to notify the user of the progress that's being made every few seconds (ex: "Generated 50000 documents out of 100000"). I create another Task, RecordProgress(), which records progress every 3 seconds.
However, if the program generates many tasks, the RecordProgress() never runs. If the program only generates 4 tasks, then RecordProgress() runs correctly ie. gets called every 3 seconds. However, if the program generates many tasks, RecordProgress() only runs once processing is/close to being finished.
Is there any way to increase the priority of the RecordProgress() task?
I've tried logging progress in each task, but that generates too many log messages to the console, which severely slows down my program.
I've tried logging in each task and waiting 3 seconds between logs, but if the program generates 50 tasks, then 50 messages will be logged to the console at the same time, which once again slows down my program and is unnecessary. I'd rather have ONE log message to the console every 3 seconds.
public void RecordProgress()
{
Stopwatch sw = new Stopwatch();
sw.Start();
//only record data while this generator is generating
while (_processing)
{
if(sw.ElapsedMilliseconds < _logFrequency)
continue;
Console.WriteLine("Generated " + _docsGenerated + " documents.");
sw.Restart();
}
}
public void GenerateDocs()
{
List<Task> tasks = new List<Task>();
_processing = true;
for (i = 0; i < 50; i ++)
{
tasks.Add(Task.Run(() => DoWork());
}
//task which records progress
//ONLY runs if not many tasks are created above
Task.Run(() => RecordProgress());
Task.WaitAll(tasks.ToArray());
}
I'd like the RecordProgress() task to run every 3 seconds regardless of the number of tasks generated by this program.
Edit: As per the comments, I removed the use of Thread.Sleep(). However, that only delayed the starting of my RecordProgress() task.
I've attempted to use a Stopwatch in RecordProgress() to only record progress every 3 seconds, but it greatly slows the performance of my program.
So new question: how to record progress of tasks without using a timer that heavily impacts performance?