thread get 100% CPU very fast

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

提交回复
热议问题