简体   繁体   中英

Getting byte array from a stream HIGH CPU usage on linux via MONO

we are using this code on windows.. on widnows it getting 0% CPU usage we are rebuilded code run into linux debian 10 and we are running it via MONO Its getting 50%+ CPU usage:(

please help, how can we solve this to get 0% cpu usage..? without thread sleep...

Many thanks for your helping !!

using System;
using System.IO;
using System.Net;
using System.Threading;

namespace cpuissues
{
    public class Rec
    {
        
        public Rec()
        {
            start();
        }
        private void start()
        {
            try
            {
                Thread httP_start = new Thread(httpStart);
                httP_start.Start();
                //httpStart();

            }
            catch (Exception ex)
            {

            }
        }


        private async void httpStart()
        {
            string url = "http://tviptv.iptv-channel.ru:8000/live/NndqUU6Xoe/mV6O7VmqLx/138.ts"; //"http://tviptv.iptv-channel.ru:8000/live/NndqUU6Xoe/mV6O7VmqLx/1.ts";

            try
            {

                // Console.WriteLine("About to open Webclient");
                WebClient client = new WebClient();

                using (Stream stream = client.OpenRead(url))
                {
                    int bytesReceived = 1316; //must be used 1316 value for our purposes
                    byte[] buffer = new byte[bytesReceived];
                    int i = 0;

                    while ((bytesReceived = stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        i = i + 1;
                        Console.WriteLine(Convert.ToString(i));
                        //Thread.Sleep(100); //DO NOT USE THIS ... ITS NOT SOLUTION we need nonstop getting data...!
                    }

                   
                }
            }
            catch (Exception e)
            {

            }
        }
    }
}

You need to actually await the read otherwise you're just constantly looping:

Change this line:

while ((bytesReceived = stream.Read(buffer, 0, buffer.Length)) != 0)

to this:

while ((bytesReceived = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)

You should also await the OpenRead :

using (Stream stream = await client.OpenReadTaskAsync(url)) 

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