为什么空白线程占用CPU的30%?

时间:2017-10-06 08:59:39

标签: c# multithreading

我写了一个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;
    }
}

1 个答案:

答案 0 :(得分:6)

  

它启动了2个新线程,它们并没有做任何重的事情

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

你应该延迟执行一点。例如,如果“不采取行动”,您可以使用Thread.Sleep(1000)来延迟执行。一秒钟。