Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. TcpClient throws exception when on worker thread

TcpClient throws exception when on worker thread

Scheduled Pinned Locked Moved C#
csharpcomquestion
1 Posts 1 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    JohnRLewis
    wrote on last edited by
    #1

    // // 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

    1 Reply Last reply
    0
    Reply
    • Reply as topic
    Log in to reply
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes


    • Login

    • Don't have an account? Register

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • World
    • Users
    • Groups