thread get 100% CPU very fast

后端 未结 5 1281
轮回少年
轮回少年 2021-01-18 07:44

I am implementing a very basic thread in C#:

private Thread listenThread;

public void startParser()
{
   this.listenThread = new Thread(new ThreadStart(chec         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 08:19

    Because your function isn't doing anything inside the while block, it grabs the CPU, and, for all practical purposes, never lets go of it, so other threads can do their work

    private void checkingData()
    {
        while (true)
        {
            // executes, immediately
        }
    }
    

    If you change it to the following, you should see more reasonable CPU consumption:

    private void checkingData()
    {
        while (true)
        {
            // read your sensor data 
    
            Thread.Sleep(1000);
        }
    }
    

提交回复
热议问题