Search code examples
c#multithreadingconsoleconsole-applicationconsole.writeline

Printing out current state of separate threads in Console application c#


I have a code which basically looks like this:

Parallel.Foreach(items,dbItem=>
{
  int counter = 0; 
  Interlocked.Increment(ref counter);
  Console.WriteLine("Current counter state: " + counter);
});

What I would like to do here is to simple re-print the counter value for specific thread that is being fired up like this:

Thread {0} - Current conter state: 1 << Value 1 gets re-printed every time this console.writeline occurs... ? 
Thread {1} - Current conter state: 1
Thread {2} - Current conter state: 1
Thread {3} - Current conter state: 1
Thread {4} - Current conter state: 1
Thread {5} - Current conter state: 1

Is this doable, if so how ?

P.S. What I ment by the value being re-printed is to show the current value of counter on each thread without doing a new console.writeline and spamming my console with bunch of same text...

P.S. 2 ,guys this is the desired output:

   Thread {1} - Current conter state: >>2<< this value here gets updated

And without having to do something like this in console:

   Thread {1} - Current conter state: 1
   Thread {1} - Current conter state: 2
   Thread {1} - Current conter state: 3
   Thread {1} - Current conter state: 4
   Thread {1} - Current conter state: 5

I would simply like to re-print the counter value in Console application...


Solution

  • So you need update a value in console? Try this code (it's just a demo):

    var counters = new ConcurrentDictionary<string, int>();
    
    var threads = Enumerable.Range(0, 5).Select(i => new Thread(() =>
    {
        var key = $"Thread {i}";
        for (var j = 0; j < 10; ++j)
        {
            var counter = j;
            counters.AddOrUpdate(key, counter, (k, v) => counter);
            Thread.Sleep(200);
        }
    })).ToList();
    threads.ForEach(t => t.Start());
    
    while (threads.Any(t => t.IsAlive))
    {
        int line = 0;
        foreach (var counter in counters)
        {
            Console.SetCursorPosition(1, line++);
            Console.WriteLine($"{counter.Key} - {counter.Value}");
            Thread.Sleep(50);
        }
    }