Marco Salerno
Marco Salerno

Reputation: 5201

Why should blank threads consume 30% of CPU?

I've wrote a c# console application.

After the boot, it starts 2 new threads which aren't doing anything heavy at all, why should this situation consume 30% of CPU?

This is my code:

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

Upvotes: 2

Views: 91

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157068

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

Uhm, I am pretty sure it says while (true) which will keep running that code until all CPU power is burned up and in that tight loop it keeps allocating (and eventually freeing) memory. There is nothing that stops that code to run as fast and as much as it can and thus to allocate massive amounts of memory in time.

You should delay the execution a bit. For example, you could use a Thread.Sleep(1000) to delay the execution in case of 'no action' by a second.

Upvotes: 6

Related Questions