开发者

NetworkStream BeginRead / EndRead

开发者 https://www.devze.com 2023-01-29 12:05 出处:网络
I\'m really new to C# programming and I\'m developing an application based on a TcpClient. I would like to know how to use BeginRead & EndRead, I\'ve already read MSN documentation but doesn\'t h

I'm really new to C# programming and I'm developing an application based on a TcpClient.

I would like to know how to use BeginRead & EndRead, I've already read MSN documentation but doesn't help.

I've this :

    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.开发者_Python百科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
    }

How can I update a Form component using result ?

Thanks for help.


First, I recommend learning a lot about multithreading. Then come back and learn about sockets. Both of these have rather steep learning curves, and trying to tackle both is a lot to handle.

That said, you can post an update to the UI by capturing the UI context via TaskScheduler.FromCurrentSynchronizationContext and scheduling a Task to that TaskScheduler. If the TPL isn't available, then you can just use SynchronizationContext directly.

0

精彩评论

暂无评论...
验证码 换一张
取 消