在控制台应用程序 c# 中打印出单独线程的当前状态

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

我的代码基本上是这样的:

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

我想在这里做的是简单地重新打印正在启动的特定线程的计数器值,如下所示:

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

这可行吗,如果可行怎么办?

P.S。我对重新打印的值表示的是在每个线程上显示计数器的当前值,而无需执行新的 console.writeline 并用一堆相同的文本向我的控制台发送垃圾邮件...

P.S。 2,伙计们,这是期望的输出:

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

无需在控制台中执行类似操作:

   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

我只想在控制台应用程序中重新打印计数器值...

所以您需要在控制台中更新一个值?试试这个代码(它只是一个演示):

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);
    }
}