如何在C#中的并行Task中通过TCP套接字接收数据?

时间:2018-07-11 09:47:17

标签: c# uwp tcpclient

我正在UWP应用程序中编写一个客户端程序,该程序通过TCP套接字从服务器接收数据,该服务器定期向该客户端发送数据。 我遇到一个问题,我想通过如下所示的Task接收数据,该任务使用LoadAsync方法循环读取数据。结果,我需要在此任务的方法和异步之前使用await。当我创建StreamSocket时  并以另一种方法调用Task,则ListenTcpClient Task在LoadAsync()方法之后返回,并且未接收到数据并在后续步骤中显示。您能告诉我如何在保持UI线程和其他线程在其他事物上正常工作的同时从TCP套接字接收数据吗? 谢谢。

public async Task ListenTcpClient(StreamSocket clientTcpSocket)
{
    while(clientTcpSocket!=null)
    {
        using (DataReader reader = new DataReader(clientTcpSocket.InputStream))
        {
            await reader.LoadAsync(sizeof(int));
            int fdToReadRcv = reader.ReadInt32();
            byte[] bs = BitConverter.GetBytes(fdToReadRcv);
            Array.Reverse(bs);
            int fdToRead = BitConverter.ToInt32(bs, 0);
            Debug.WriteLine(fdToRead);
            StartButton1.Content = fdToRead;
        }
    }
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
    clientTcpSocket = new StreamSocket();
    try
    {// create the socket
        await clientTcpSocket.ConnectAsync(new HostName(ip), tcpPort);
        using (DataReader reader = new DataReader(clientTcpSocket.InputStream))
        {
            await reader.LoadAsync(sizeof(int));
            int fdToReadRcv = reader.ReadInt32();
            byte[] bs = BitConverter.GetBytes(fdToReadRcv);
            Array.Reverse(bs);
            int fdToRead = BitConverter.ToInt32(bs,0);
            Debug.WriteLine(fdToRead);
        }
        using (DataWriter writer = new DataWriter(clientTcpSocket.OutputStream))
        {
            writer.WriteString(String.Format("Client Start"));
            await writer.StoreAsync();
        }
        timer.Start();
        ListenTcpClient(clientTcpSocket);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
    //then do something else while the client socket is receiving data
}

1 个答案:

答案 0 :(得分:0)

只要Task彼此独立,就可以使用Task.WhenAll(...)并行运行它

private async void Button_Click(object sender, RoutedEventArgs e)
{
        // generate a create socket task
        var createSocketTask = CreateSocket();

        // create 'do something else' task
        var doSomethingElseTask = DoSomethingElse();

        // run both tasks in parallel
        await Task.WhenAll(createSocketTask, doSomethingElseTask);
}

private async Task CreateSocket()
{
    clientTcpSocket = new StreamSocket();
    try
    {// create the socket
        await clientTcpSocket.ConnectAsync(new HostName(ip), tcpPort);
        using (DataReader reader = new DataReader(clientTcpSocket.InputStream))
        {
            await reader.LoadAsync(sizeof(int));
            int fdToReadRcv = reader.ReadInt32();
            byte[] bs = BitConverter.GetBytes(fdToReadRcv);
            Array.Reverse(bs);
            int fdToRead = BitConverter.ToInt32(bs,0);
            Debug.WriteLine(fdToRead);
        }
        using (DataWriter writer = new DataWriter(clientTcpSocket.OutputStream))
        {
            writer.WriteString(String.Format("Client Start"));
            await writer.StoreAsync();
        }
        timer.Start();
        ListenTcpClient(clientTcpSocket);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
}

 private async Task DoSomethingElse()
 {
        // do something
 }