Parallel.Foreach没有完成流

时间:2014-03-26 10:49:32

标签: c# .net task-parallel-library

为了进行负载测试,我需要模拟多个用户同时尝试登录系统。我有另一个开发人员编写的代码,可以向系统发送登录请求。使用ok登录,它还将返回xml中的其他信息。

我尝试过使用Parallel.ForEach,但对并行编程没有任何实际经验:

   Parallel.ForEach(clientList, client =>
      {

         RunTest(client);

        });
    public void RunTest(object data)
    {
        if (!(data is IGprsClient))
        {
            return;
        }

        _noRunningTests += 1;

        IGprsClient gprsClient = data as IGprsClient;


        DateTime startTime = DateTime.Now;

        Log(gprsClient.Id, "Test started.");

        bool result = gprsClient.StartTest(20000);

        DateTime endTime = DateTime.Now;

        TimeSpan diff = endTime - startTime;

        if (result == false)
        {
            Log(gprsClient.Id, "Test failed.");
        }

        Log(gprsClient.Id, "Test took {0}ms. ", (int)diff.TotalMilliseconds);


        _noRunningTests -= 1;
    }

    override public bool StartTest(int timeout)
    {
        _testStarted = true;

        try
        {
            LogDebug("Trying to connect.");
            _client = new TcpClient(ipAddress, port);

            LogDebug("Connected.");

            bool result = false;

            //Todo: insert testcase into client
            switch (TestCaseName)
            {
                case "LoginTEST":
                    var testCase = new LoginTEST(this);
                    result = testCase.Execute(user, pwd, phoneNum);
                    break;

                default:
                    Log("Unknown test case: " + TestCaseName);
                    break;
            }

            _client.Close();
            return result;
        }
        catch (Exception ex)
        {
            if (_client != null)
                _client.Close();
            Log(ex.Message);
            return false;
        }
    }

反过来会发送请求并阅读回复。

    public bool Execute(string user, string pwd, string phoneNum)
    {
        SendDataListRequest(userId);
        string requiredDataResponse = Client.ReadMsg();
        return true;

    }

运行测试将发送请求并按如下方式读取消息:

    public string ReadMsg()
    {            
        int msgLength = -1;
        var stream = _client.GetStream();

        while (_testStarted)
        {
            int b = stream.ReadByte();

            if (b == -1)
            {
                return "";
            }
            else if (b == 0x02 || msgLength == -1)
            {
                while (b != 0x02 && _testStarted)
                {
                    b = stream.ReadByte(); // Finds the start token

                    if (b == -1)
                    {
                        return "";
                    }
                }
                msgLength = 0; // Starts collecting data

            }
            else if (b == 0x03)
            {
                byte[] encryptedMsg = Convert.FromBase64String(
                        Encoding.UTF8.GetString(byteBuffer, 0, msgLength));

                byte[] decryptedMsg = SttCipher.DecryptMessage(encryptedMsg);

                MemoryStream ms = new MemoryStream(decryptedMsg);
                GZipStream gZipStream = new GZipStream(ms, CompressionMode.Decompress, true);
                var bufLen = ReadAllBytesFromStream(gZipStream, decompressedBuffer);
                gZipStream.Close();

                string completeMsg = Encoding.UTF8.GetString(decompressedBuffer, 0, bufLen);

                if (completeMsg.Length < 500)
                    LogDebug("Received XML-data:\n{0}", completeMsg);
                else
                    LogDebug("Received XML-data: {0} bytes\n{1}...", completeMsg.Length, completeMsg.Substring(0, 500));

                return completeMsg;
            }
            else
            {
                if (byteBuffer.Length <= msgLength)
                {
                    throw new Exception("XML message too long!");
                }

                byteBuffer[msgLength] = (byte)b;
                msgLength++;
            }
        }
        return "";
    }

运行一个客户端很好,将等待响应。问题在于几个客户,响应被切断了。让我在响应中留下未封闭的xml。但是我不知道为什么。有没有人有合理的解释和/或解决方案或更好的方法呢?

0 个答案:

没有答案