简体   繁体   中英

Reduce C# Application CPU Usage

["

I am creating a program that will TCP Event Receiver.<\/i>

namespace TCPIPReceiver

TL; DR: your code is inefficiently handling TCP I/O by spamming new reader threads. This can lead to high RAM usage, page faults and ultimately high CPU-use due to Windows memory compression


Re update, I can see now that your BackgroundWorker is spamming a new thread to INCOMINGTHREAD() whenever data is ready to be read on the SimpleTcpServer .

Apart from being highly inefficient, depending on exactly how long INCOMINGTHREAD() takes to complete and for the thread to be released, you could exhaust the available threads for your process (and perhaps Windows entirely?) very quickly.

Excessive threads and RAM

Each Windows thread consumes 1 MB of RAM and so creating excessive threads has a follow-on effect of consuming excessive RAM. The OS will try to satisfy your request by requesting memory as well as a logical thread. As the demand for threads increases and depending on your system and version of Windows, as you approach the RAM limit certain versions of Windows 10 will start to compress memory in order to save space. Now we're in for real trouble as in order to reduce memory pressure, Windows will compress memory and this has an impact on the CPU !

I've seen quite a few business laptops with say 16 GB RAM being used for development to max out on both RAM and CPU rather quickly with the former having a direct impact on the latter.

Alternatives

Instead of using BackgroundWorker and new Thread() you should look into using asynchonous I/O via async/await and the equivalent async members of SimpleTcpServer (if any).

Alternatively use the older TcpListener as it supports asynchronous operation. This class may not have built-in Task -awareness but you can easily create a Task-based Asynchronous Pattern (TAP) for it .

In doing this you vastly reduce the amount of threads your app needs, the CPU time involved, memory requirements and reduction in possible Windows 10 memory compression activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM