日期:2014-05-20  浏览次数:20858 次

关于多线程同步的问题,精通多线程机制的请进
做的一个网络同步采集数据的程序,思路是缓冲区数据超过260个字节后开始处理。由于NetworkStream不支持获取缓冲区字节数,所以我想自己写个类,通过一个自定义缓冲区来达到支持的目的。代码如下:
C# code
 
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace CaijiTest
{
    class NetReceiveBuffer
    {
        TcpClient tc;
        int BufferLength;
        byte[] NetBuffer;
        NetworkStream netStream;
        Thread thread;
        ThreadStart ts;
        int iPosition=0;
        byte bt;
        public NetReceiveBuffer(string ip,int port,int length)
        {
            BufferLength = length;
            NetBuffer = new byte[length];
            tc = new TcpClient(ip, port);
            netStream = tc.GetStream();
            ts = new ThreadStart(Receive);
            thread = new Thread(ts);
            thread.Start();
        }

        public int BytesToRead
        {
            get
            {
                return iPosition;
            }
        }

        private void Receive()
        {
            while (true)
            {
                Thread.Sleep(1);
                NetBuffer[iPosition] = (byte)netStream.ReadByte();
                iPosition++;
                if (iPosition == NetBuffer.Length)
                {
                    Buffer.BlockCopy(NetBuffer, 1, NetBuffer, 0, NetBuffer.Length - 1);//丢弃第一个字节,后续数据向前移动一个字节
                    iPosition--;//回到缓冲区最后一个字节的位置
                }
            }
        }

        public void Read(byte[] buffer, int offset, int size)
        {
            lock (this)
            {
                Buffer.BlockCopy(NetBuffer, 0, buffer, offset, size);
                Buffer.BlockCopy(NetBuffer, size, NetBuffer, 0, iPosition - size);
                iPosition -= size;
            }
        }

        public byte ReadByte()
        {
            lock (this)
            {
                bt = NetBuffer[0];
                Buffer.BlockCopy(NetBuffer, 1, NetBuffer, 0, iPosition - 1);//丢弃第一个字节,后续数据向前移动一个字节