网络流多个线程并传输数据

时间:2019-02-25 20:28:52

标签: c# wpf multithreading tcp networkstream

我有一个使用Networkstream与服务器通信的应用程序。读写发生在两个不同的线程上。一个线程始终在侦听来自服务器的数据,另一个线程将数据写入流以发送请求。然后,服务器处理数据,然后发送回订单号,但是由于我在两个线程上进行写入和读取,因此无法在最初将数据发送到服务器的线程上读取。

我的问题是,我为发送到服务器的每个请求创建一个listviewitem,并且我需要以某种方式标识与接收到的订单号相对应的listviewitem。

private void SendCheckoutData()
    {
        //Start sending data
        manager.SendInt(TableId);
        Thread.Sleep(80);
        manager.SendInt(ClientId);
        Thread.Sleep(80);
        manager.SendInt(ListViewCheckoutTable.Items.Count);
        Thread.Sleep(80);
        manager.SendInt(GetCombinedPrice());
        Thread.Sleep(80);

        int NumberOfItems = 0;

        for (int i = 0; i < ListViewCheckoutTable.Items.Count; i++)
        {
            OrderMenuItem item = (OrderMenuItem)ListViewCheckoutTable.Items.GetItemAt(i);
            manager.SendInt(item.Id);
            Thread.Sleep(80);
            manager.SendInt(item.Quantity);
            Thread.Sleep(80);
            NumberOfItems += item.Quantity;
        }

        int OrderNumber; //The variable I somehow need to assign the value to

        ListViewPendingOrders.Items.Add(new PendingOrderMenuItem { OrderNumber = OrderNumber, Quantity = NumberOfItems, TotalPrice = GetCombinedPrice() });
    }

TCPManager

class TCPManager
{
    private readonly string ip;
    private readonly int port;

    TcpClient client;
    NetworkStream stream;

    Task ListenerTask;
    CancellationTokenSource cancelToken = new CancellationTokenSource();

    public TCPManager(string ip, int port)
    {
        this.ip = ip;
        this.port = port;
    }

    public void Connect()
    {
        client = new TcpClient(ip, port);
        stream = client.GetStream();
    }

    public void Disconnect()
    {
        cancelToken.Cancel();

        while (!ListenerTask.IsCompleted)
        {
            Thread.Sleep(10);
        }

        stream.Close();
        client.Close();
    }

    public void ReadData()
    {
        ListenerTask = new Task(() =>
        {
            while (true)
            {
                while (!stream.DataAvailable)
                {
                    Thread.Sleep(100);
                }
                Thread.Sleep(100);

                StartNewTask(GetInt());
            }

        }, cancelToken.Token, TaskCreationOptions.LongRunning);
    }

    private void StartNewTask(int request)
    {
        switch (request)
        {
            case RequestIds.REQUEST_ORDERNUMBER:

                break;

            case RequestIds.REQUEST_ORDER_COMPLETED:
                break;
        }
    }
public int GetInt()
        {
            byte[] bData = new byte[sizeof(int)];
            stream.Read(bData, 0, bData.Length);
            int Data = BitConverter.ToInt32(bData, 0);

            return Data;
        }

0 个答案:

没有答案