Reading on a NetworkStream = 100% CPU usage

后端 未结 3 974
忘了有多久
忘了有多久 2020-12-19 15:07

I am reading from a NetworkStream that is in a while loop. The issue is I am seeing 100% CPU usage. Is there any way to stop this from happening?

Here is what I have

3条回答
  •  佛祖请我去吃肉
    2020-12-19 15:42

    The reason you are seeing 100% CPU usage, is that you're always doing something, which is a result of your endless while loop with no delays.

    The basic semantics are:

    1. Check if client is connected
    2. Poll the client
    3. Check if data is available
    4. Read the data
    5. Go back to step 1

    Since you're in this loop, you're always doing something, whatever it is. The easiest semantic is to do a Thread.sleep() at the end of your loop. This will help you without having to make many changes. However, you will introduce a delay of whatever that sleep time is, and isn't really a proper way (but may suit your situation).

    The proper method is to learn about asynchronous sockets if you want a high performance server, or something that uses suitable low CPU when 1 or more sockets are connected. Doing a quick Google search is probably best to learn, I don't recall any particularly good articles off hand. The benefit of Asynchronous IO is basically that you will only use CPU time when you have something to do. When data is received, your method will be called to do whatever processing you have to do.

提交回复
热议问题