gpt4 book ai didi

c# - 为什么空白线程要占用 30% 的 CPU?

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

我编写了一个 C# 控制台应用程序。

启动后,它启动了 2 个新线程,它们根本没有做任何繁重的事情,为什么这种情况会消耗 30% 的 CPU?

这是我的代码:

class Program
{
static DateTime LastPlayerRegistration;
static List<Player> Players;
static List<string> CommandsList = new List<string>
{
"GetPlayersNumber", "GetLastRegistration", "GetTimeElapsed", "NewPlayer"
};
static void Main(string[] args)
{
if (!File.Exists("Players.json")) File.Create("Players.json");
Players = JsonConvert.DeserializeObject<List<Player>>(File.ReadAllText("Players.json")) ?? new List<Player>();
new Thread(PlayerInput).Start();
new Thread(GeneralRoutines).Start();
}

static void PlayerInput()
{
while (true)
{
string command = Console.ReadLine();
string[] commandParameters = command.Split(' ');
switch (commandParameters[0].ToLower())
{
case "getplayersnumber":
Console.WriteLine("There are " + Players.Count + " players registered!");
break;
case "getlastregistration":
Console.WriteLine("Last registration happened at " + LastPlayerRegistration);
break;
case "gettimeelapsed":
Console.WriteLine((DateTime.Now - LastPlayerRegistration) + " time elapsed from last registration");
break;
case "newplayer":
if (commandParameters.Count() > 1 && !string.IsNullOrEmpty(commandParameters[1]))
{
DateTime now = DateTime.Now;
TimeSpan elapsed = (now - LastPlayerRegistration);
LastPlayerRegistration = now;
Players.Add(new Player(commandParameters[1], elapsed));
Console.WriteLine("Player " + commandParameters[1] + " created!");
}
else
{
Console.WriteLine("Player Name is missing!");
}
break;
default:
Console.WriteLine("'" + command + "' command is not defined.");
break;
}
}
}

static void GeneralRoutines()
{
DateTime lastPlayersListSave = DateTime.Now;
while (true)
{
if ((int)(DateTime.Now - lastPlayersListSave).Seconds >= 30)
{
File.WriteAllText("Players.json", JsonConvert.SerializeObject(Players));
Console.WriteLine("Players list saved!");
lastPlayersListSave = DateTime.Now;
}
}
}
}

class Player
{
public Guid ID { get; set; }
public string Name { get; set; }
public TimeSpan Elapsed { get; set; }

[JsonConstructor]
public Player(Guid id, string name, TimeSpan elapsed)
{
this.ID = id;
this.Name = name;
this.Elapsed = elapsed;
}
public Player(string name, TimeSpan elapsed)
{
this.ID = Guid.NewGuid();
this.Name = name;
this.Elapsed = elapsed;
}
}

最佳答案

it starts 2 new threads which aren't doing anything heavy at all

嗯,我很确定它说的是 while (true) 这将继续运行该代码,直到所有 CPU 能力都被耗尽,并且在那个紧密的循环中它会不断分配(并最终释放)内存。没有什么可以阻止该代码尽可能快地运行,从而及时分配大量内存。

你应该稍微延迟执行。例如,您可以使用 Thread.Sleep(1000) 在“无操作”的情况下延迟执行一秒钟。

关于c# - 为什么空白线程要占用 30% 的 CPU?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46602060/

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