gpt4 book ai didi

c# - 每 n 秒更新一次对象状态

转载 作者:行者123 更新时间:2023-11-30 23:11:19 25 4
gpt4 key购买 nike

我有 worker 类(Class),他们的工作是开始whileloop。我有工作类列表,每个工作类都在自己的线程上运行。每 n 秒我应该能够为每个 worker 打印循环次数。我的意图是在 n 秒后(例如 20 秒)打印有关每个 worker 的信息
worker1 - noOfLoops - 10
worker2 - noOfLoops - 20
workern - noOfLoops - 30
我怎样才能做到这一点。代码片段

class Program
{
static void Main(string[] args)
{
List<IWorkerClass> workerClasses = new List<IWorkerClass>();
for (int i = 0;i<5; i++)
{
workerClasses.Add(new WorkerClass("worker" + i.ToString()));
}

foreach(IWorkerClass wc in workerClasses)
{
IWorkerClass temp = wc;
Thread workerThread = new Thread(() => wc.StartWhileLoop());
workerThread.Start();
}
Console.ReadKey();
}
}
public interface IWorkerClass
{
int noOfLoops { get; set; }
void StartWhileLoop();
}

public class WorkerClass : IWorkerClass
{
string _name = string.Empty;
public WorkerClass(string name)
{
this._name = name;
}
public int noOfLoops{get;set;}

public void StartWhileLoop()
{
while(true)
{
Thread.Sleep(3000);
noOfLoops += 1;
}
}
}
}

最佳答案

下面的代码保留您现有的结构并创建一个新线程,该线程执行 ThreadReader 以每 20 秒向每个工作人员询问其进度。

using System;
using System.Collections.Generic;
using System.Threading;

class Program
{
static void Main(string[] args)
{
List<IWorkerClass> workerClasses = new List<IWorkerClass>();
for (int i = 0; i < 5; i++)
{
workerClasses.Add(new WorkerClass("worker" + i.ToString()));
}

foreach (IWorkerClass wc in workerClasses)
{
IWorkerClass temp = wc;
Thread workerThread = new Thread(() => temp.StartWhileLoop());
workerThread.Start();
}

Thread checkerThread = new Thread(() => ThreadReader(workerClasses));
checkerThread.Start();

Console.ReadKey();
}

static void ThreadReader(List<IWorkerClass> workers)
{
while (true)
{
foreach (var worker in workers)
{
Console.WriteLine($"{worker.name} - {worker.noOfLoops}");
}

Thread.Sleep(20000);
}
}
}
public interface IWorkerClass
{
string name { get; set; }
int noOfLoops { get; set; }
void StartWhileLoop();
}

public class WorkerClass : IWorkerClass
{
public string name { get; set; }
public WorkerClass(string name)
{
this.name = name;
}
public int noOfLoops { get; set; }

public void StartWhileLoop()
{
while (true)
{
Thread.Sleep(3000);
noOfLoops += 1;

}
}
}

关于c# - 每 n 秒更新一次对象状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44757418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com