NetworkStream BeginRead / EndRead

时间:2010-12-09 15:31:01

标签: c# winforms tcp tcpclient

我是C#编程的新手,我正在开发一个基于TcpClient的应用程序。

我想知道如何使用BeginRead& EndRead,我已经阅读过MSN文档,但没有帮助。

我有这个:

    private void Send()
    {
        TcpClient _client = new TcpClient("host", 80);
        NetworkStream ns = _client.GetStream();
        ns.Flush();
        / ...
        ns.Write(buffer, 0, buffer.Length);

        int BUFFER_SIZE = 1024;
        byte[] received = new byte[BUFFER_SIZE];
        ns.BeginRead(received, 0, 0, new AsyncCallback(OnBeginRead), ns);
    }

    private void OnBeginRead(IAsyncResult ar)
    {
        NetworkStream ns = (NetworkStream)ar.AsyncState;
        int BUFFER_SIZE = 1024;
        byte[] received = new byte[BUFFER_SIZE];
        string result = String.Empty;

        ns.EndRead(ar);

        int read;
        while (ns.DataAvailable)
        {
            read = ns.Read(received, 0, BUFFER_SIZE);
            result += Encoding.ASCII.GetString(received);
            received = new byte[BUFFER_SIZE];
        }
        result = result.Trim(new char[] { '\0' });
        // Want to update Form here with result
    }

如何使用结果更新表单组件?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

首先,我建议学习很多关于多线程的知识。然后回来学习插座。这两个都有相当陡峭的学习曲线,试图解决这两个问题是要处理的 lot

也就是说,您可以通过TaskScheduler.FromCurrentSynchronizationContext捕获UI上下文并将Task安排到TaskScheduler来向UI发布更新。如果TPL不可用,那么您可以直接使用SynchronizationContext