强制执行代码直到方法结束

时间:2013-04-24 09:56:56

标签: c# multithreading sockets delay delayed-execution

我正在研究客户端 - 服务器多线程应用程序:

沟通的进展是:

  1. 服务器侦听套接字
  2. 客户端连接并向服务器发送请求
  3. 每个请求以0x04
  4. 结束
  5. 服务器必须使用比传入请求慢的操作来执行每个请求
  6. 我在“ProcessClient”方法中遇到问题,当两个请求在短时间内发生,并且第一个请求无法处理直到方法结束,因为第二个请求即将进行处理。 foreach循环后出现问题:

                foreach (var t in invoices)
                {
                    SaveToDataBase(t);
                }
    

    方法直到最后才执行,并且它不会向客户端发送响应,并带有以下代码片段:

                var ResponseFile = ResponseClientFolder + "\\" + ResponseClientFileName + x + ".txt";
                StreamWriter sw = File.CreateText(ResponseFile);
                sw.WriteLine(_odgovor);
                sw.Close();
                _odgovor = string.Empty;
                SendToClient(ResponseFile);
    

    因为“ProcessClient”方法发生了第二次请求。

    有没有办法解决这个问题。我一直在寻找很多没有成功的解决方案。

    整个代码如下:

        private void RunListener()
        {
            try
            {
                _listener = new TcpListener(IPAddress.Parse(ServerAddres), ServerPort);
                _listener.Start();
                while (true)
                {
                    TcpClient client = _listener.AcceptTcpClient();
                    Invoke(new Action(() => { }));
                    ThreadPool.QueueUserWorkItem(ProcessClient, client);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, @"Run listener");
            }
        }
    
    
        private void ProcessClient(object state)
        {
            try
            {
                byte[] bytes = new byte[1024];
                TcpClient client = state as TcpClient;
                StringBuilder completeMessage = new StringBuilder();
    
                if (client == null) return;
    
                networkStream = client.GetStream();
                int bytesRead = 0;
                do
                {
                    bytesRead = networkStream.Read(bytes, 0, bytes.Length);
                    completeMessage.AppendFormat("{0}", Encoding.Default.GetString(bytes, 0, bytesRead));
                } while (bytesRead > 0 && bytes[bytesRead - 1] != 0x04);
    
                completeMessage = completeMessage.Replace(@"”", "");
    
                string datetime = DateTime.Now.ToString();
                var x = datetime.Replace(".", string.Empty).Replace(":", string.Empty).Replace(" ", string.Empty);
                var inputfilename = "Racun" + x + ".txt";
    
                StreamWriter sws = File.CreateText(inputfilename);
                sws.WriteLine(completeMessage);
                sws.Close(); 
                string data = completeMessage.ToString();
                char[] delimiters = { '\r', '\n' };
                string[] invoices = data.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
    
                foreach (var t in invoices)
                {
                    SaveToDataBase(t);
                }
    
                var ResponseFile = ResponseClientFolder + "\\" + ResponseClientFileName + x + ".txt";
                StreamWriter sw = File.CreateText(ResponseFile);
                sw.WriteLine(_odgovor);
                sw.Close();
                _odgovor = string.Empty;
                SendToClient(ResponseFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, @"Proces client");
            }
        }
    
        private void SendToClient(string ResponseFile)
        {
            try
            {
                byte[] byteData = File.ReadAllBytes(ResponseFile);
                List<byte> byteDat = new List<byte>();
                byteDat.AddRange(byteData);
                byteDat.Add(0x04);
    
                byteData = byteDat.ToArray();
                networkStream.Write(byteData, 0, byteData.Length);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, @"Send to client");
            }
        }
    

0 个答案:

没有答案