具有高CPU的多线程TCP服务器并保持增加线程数

时间:2016-03-04 01:51:20

标签: c# .net multithreading server

我编写了简单的多线程TCP C#Server程序。运行程序后,我的CPU使用率很高,并且任务管理器中的线程数不断增加。任何人都可以帮我弄清楚如何解决和提出建议?

这是我的代码。

public class Program
{
    static void Main(string[] args)
    {
        int _Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TCPPort"]);
        string _IP = System.Configuration.ConfigurationManager.AppSettings["TCPIP"];
        TcpServer server = new TcpServer(_Port);
    }
}

public class TcpServer
{
    private TcpListener _server;
    private Boolean _isRunning;
    private static int defaultMax = 8;
    public TcpServer(int port)
    {
        _server = new TcpListener(IPAddress.Any, port);
        _server.Start();
        _isRunning = true;          
        LoopClients();
    }

    public void LoopClients()
    {
        while (_isRunning)
        {

            TcpClient newClient = _server.AcceptTcpClient();
            SentFirstTimeData_New(newClient);
            Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
            t.Start(newClient);
        }
    }

    public void HandleClient(object obj)
    {
        int requestCount = 0;
        byte[] bytesFrom = new byte[209666];
        string dataFromClient = null;
        Byte[] sendBytes = null;
        requestCount = 0;
        int byteread = 0;
        string respdata = string.Empty;
        byte[] buffer = new byte[4096];
        int numberOfBytesRead;

        TcpClient client = (TcpClient)obj;         
        NetworkStream networkStream = client.GetStream();
        IPAddress address = ((IPEndPoint)client.Client.RemoteEndPoint).Address;

        Boolean bClientConnected = true;
        int id = Thread.CurrentThread.ManagedThreadId;
        while (bClientConnected)
        {
            try {
                if (networkStream.DataAvailable)
                {
                    byteread = networkStream.Read(bytesFrom, 0, (int)client.ReceiveBufferSize);
                    dataFromClient = Encoding.ASCII.GetString(bytesFrom).TrimEnd('\0');
                    System.Text.Encoding.ASCII.GetString(bytesFrom);

                    XmlDocument doc = new XmlDocument();
                    string xml = Encoding.UTF8.GetString(bytesFrom).TrimEnd('\0');
                    doc.LoadXml(xml);
                    XElement incc = XElement.Load(new XmlNodeReader(doc));
                    respdata = AysncTCPIncomeString(incc);

                    sendBytes = Encoding.ASCII.GetBytes(respdata);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                }
            }
            catch (Exception ex)
            {
                Helper.WriteLog("Exception=" + ex.Message);
            }
        }
    }

    public void SentFirstTimeData_New(TcpClient tc)
    {
        try
        {
            int threadid = Thread.CurrentThread.ManagedThreadId;
            string Msg = HLStatusResponse.FirstTimeStatusSuccessfulResponse("STATUS", "1");
            NetworkStream _NetworkStream = tc.GetStream();
            if (_NetworkStream != null)
            {
                byte[] data = Encoding.ASCII.GetBytes(Msg);
                _NetworkStream.Write(data, 0, data.Length);

                Helper.WriteLog("ThreadId=" + threadid.ToString() + ";SentFirstTimeData :\t " + Msg);
            }
        }
        catch (Exception ex)
        {
            Helper.WriteLog("Sent Though Tcp Eror :" + ex.ToString());
        }
    }
}

1 个答案:

答案 0 :(得分:1)

考虑这段代码:

    Boolean bClientConnected = true;
    int id = Thread.CurrentThread.ManagedThreadId;
    while (bClientConnected)
    {
        try {
            if (networkStream.DataAvailable)

你永远不会改变bClientConnected - 它总是正确的,所以你的循环永远不会退出。

此外,如果连接处于空闲状态 - 也就是说,如果networkStream.DataAvailable为false - 那么您只需在while循环中旋转即可。

如果每个客户端都有一个线程,为什么不通过从套接字执行读取来阻止线程?然后线程不会旋转浪费cpu什么也不做。