Using TcpListener.AcceptSocket(); in a separate thread causes the thread to block?

后端 未结 2 1307
渐次进展
渐次进展 2021-01-21 12:00

I have tried to work around this as well as debug but I\'m at a loose end here :( is there any alternative to using this to check for a client connection? This code works fine i

2条回答
  •  渐次进展
    2021-01-21 12:43

    It is supposed to block. From MSDN:

    AcceptSocket is a blocking method that returns a Socket that you can use to send and receive data. If you want to avoid blocking, use the Pending method to determine if connection requests are available in the incoming connection queue.

    You can turn your whole implementation to use the async version: AcceptSocketAsync. Note this wont block your method, it will yield control back to the caller until a new Socket has been connected.

    private async void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        await WorkingAsync();
    }
    

    And inside WorkingAsync:

    private Task WorkingAsync
    {
        // Do all other stuff,
    
        Socket socket = await myList.AcceptSocketAsync();
    
       // Do rest of stuff with the socket
    }
    

    I recommend you like at What is the async/await equivalent of a ThreadPool server? for a full implementation of an async tcp connection handler

提交回复
热议问题