thread get 100% CPU very fast

后端 未结 5 1204
轮回少年
轮回少年 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:01

    while (true) is what killing your CPU.

    You can add Thread.Sleep(X) to you while to give CPU some rest before checking again.

    Also, seems like you actually need a Timer.

    Look at one of the Timer classes here http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx.

    Use Timer with as high pulling interval as you can afford, 1 sec, half a sec.
    You need to tradeoff between CPU usage and the maximum delay you can afford between checks.

    0 讨论(0)
  • 2021-01-18 08:03

    Let your loop sleep. It's running around and around and getting tired. At the very least, let it take a break eventually.

    0 讨论(0)
  • 2021-01-18 08:05

    If you're polling for a condition, definitely do as others suggested and put in a sleep. I'd also add that if you need maximum performance, you can use a statistical trick to avoid sleeping when sensor data has been read. When you detect sensor data is idle, say, 10 times in a row, then start to sleep on each iteration again.

    0 讨论(0)
  • 2021-01-18 08:18

    you can use blocking queue. take a item from blocking queue will block the thread until there is a item put into the queue. that doesn't cost any cpu.

    with .net4, you can use BlockingCollection http://msdn.microsoft.com/en-us/library/dd267312.aspx

    under version 4, there is not blocking queue int .net framework.

    you can find many implements of blocking queue if you google it.

    here is a implementation

    http://www.codeproject.com/KB/recipes/boundedblockingqueue.aspx

    by the way. where does the data you wait come from?

    EDIT

    if you want to check file. you can use FileSystemWatcher to check it with thread block.

    if your data comes from external API and the api doesn't block the thread, there is no way to block the thread except use Thread.Sleep

    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题