2010-12-09 139 views
1

我真的很陌生,我正在開發一個基於TcpClient的應用程序。NetworkStream BeginRead/EndRead

我想知道如何使用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 
    } 

如何使用結果我更新表單組件?

感謝您的幫助。

+0

這是Winforms嗎? – CodingGorilla 2010-12-09 15:41:44

+0

是的,它是WinForms。 – 2010-12-09 15:54:06

回答

1

首先,我推薦學習很多關於多線程的知識。然後回來,瞭解套接字。這兩個都有相當陡峭的學習曲線,並試圖解決這兩個問題是lot要處理。

也就是說,您可以通過TaskScheduler.FromCurrentSynchronizationContext捕獲UI上下文並將Task安排到該TaskScheduler來更新UI。如果TPL不可用,那麼您可以直接使用SynchronizationContext