TcpClient throws exception when on worker thread
-
// // What am I doing wrong here? // using System; using System.Net.Sockets; using System.Threading; class Class1 { [STAThread] static void Main(string[] args) { WorkerClass w = new WorkerClass(); // If I call the Start method on the // main thread, the code works properly // w.Start(); // But I want to run the code on a own worker thread. // However, the code will throw an exception. // Unhandled Exception: System.IO.IOException: // Unable to read data from the transport connection. // ---> System.Net.Sockets.SocketException: // The I/O operation has been aborted because of either a thread exit or an application request Thread workerThread = new Thread(new ThreadStart(w.Start)); workerThread.Start(); Console.ReadLine(); } } class WorkerClass { private TcpClient tcp; private AsyncCallback readCallback; private byte[] buffer; public void Start() { buffer = new byte[1024]; readCallback = new AsyncCallback(ReadComplete); tcp = new TcpClient(); tcp.Connect("www.microsoft.com", 80); byte[] request = System.Text.ASCIIEncoding.ASCII.GetBytes("GET /\n\n"); tcp.GetStream().Write(request, 0, request.Length); ReadStart(); } private void ReadStart() { tcp.GetStream().BeginRead(buffer, 0, buffer.Length, readCallback, null); } private void ReadComplete(IAsyncResult ar) { int bytesRead = tcp.GetStream().EndRead(ar); Console.WriteLine("{0} bytes read.", bytesRead); if (tcp.GetStream().DataAvailable) ReadStart(); } } --- John R. Lewis john@aspZone.com