Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

asp.net - C# TCP Client using high CPU when launched with Process.Start

I have an ASP Net Core 3.1 web app which launches a console app on startup...

Process p = new Process ();
p.StartInfo.FileName = Path.Combine ( env.ContentRootPath , "MyProcess" , "myprocess.exe" );
p.Start ();

The process launched listens for TCP connections like this:

while ( true )
{
     if ( theTcpListenerServer.Pending() )
     {
         Task.Run(() =>
         {
            using ( TcpClient client = theTcpListenerServer.AcceptTcpClient() )
            {
                try
                {
                    byte[] aByteArray = new byte[ client.SendBufferSize ];

                    theStream = client.GetStream()
                    int aRecv;

                    while ( true )
                    {
                        aRecv = theStream.Read(aByteArray , 0 , client.SendBufferSize);
                        aData = System.Text.Encoding.ASCII.GetString(aByteArray , 0 , aRecv);

                        if ( !string.IsNullOrEmpty(aData) )
                        {
                            RaisePackageReceivedEvent(aData);
                            break;
                        }
                    }
                }
                catch ( Exception e )
                {
                    //log some info
                }
            }
        });
    }
    Thread.Sleep(10);
}

This process runs on pretty much 0% CPU if I launch it standalone, but launching it from the web app makes it use like 30% CPU. Originally the code did not have the Task.Run bit and I also added the Thread.Sleep(10). I tried redirecting output as well when I call Process.Start, but nothing helped.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You would want to call theTcpListenerServer.AcceptTcpClient() before you spawn off the task. Then process the received client in the task. No need to call theTcpListenerServer.Pending(), that will waste cpu cycles. AcceptTcpClient will do the right thing and use minimal CPU while blocking and waiting for a connection.

Either way, this seems like something you could just spawn in a task directly in your web app. No need for another process.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...