Example #1
0
        private void DoBeginRead(object state)
        {
            bool forceClose = true;

            try
            {
                var ar = _stream.BeginRead(_bytes, 0, _bytes.Length, null, null);
                ThreadPool.RegisterWaitForSingleObject(ar.AsyncWaitHandle, EndRead, ar, _interval, true);
                forceClose = false;
            }
            catch (IOException e)
            {
                if (!_errorProvider.TryCapture(e, true))
                {
                    throw;
                }
            }
            finally
            {
                if (forceClose)
                {
                    _stream.Close();
                    _client.Close();
                }
            }
        }
        private void SendMetric()
        {
            var           metric        = int.MinValue;
            TcpClient     tcpClient     = null;
            NetworkStream networkStream = null;

            while (true)
            {
                try
                {
                    tcpClient = new TcpClient();
                    tcpClient.Connect(_endPoint);
                    networkStream = tcpClient.GetStream();
                    while (true)
                    {
                        var bytes = BitConverter.GetBytes(metric++);
                        networkStream.Write(bytes, 0, bytes.Length);
                        networkStream.Flush();
                        Console.WriteLine(
                            string.Format(CultureInfo.InvariantCulture,
                                          "{0:dd.MM.yyyy HH:mm:ss.fff} {1}", DateTime.Now, metric));
                        _waitHandle.WaitOne();
                    }
                }
                catch (IOException ioException)
                {
                    if (!_errorProvider.TryCapture(ioException, false))
                    {
                        throw;
                    }
                }
                catch (SocketException socketException)
                {
                    _errorProvider.WriteException(socketException);
                }
                finally
                {
                    if (networkStream != null)
                    {
                        networkStream.Dispose();
                        networkStream = null;
                    }
                    if (tcpClient != null)
                    {
                        tcpClient.Close();
                        tcpClient = null;
                    }
                }
                _waitHandle.WaitOne();
            }
        }