Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely timeout ReadLine on a network stream

How can I safely timeout the following code?

var client = new TcpClient("localhost", 6000);
new StreamReader(client.GetStream()).ReadLine(); // close the client if no line arrives after 5 seconds...

Previously I had a timer running on another thread which called client.Close() if the timeout expired, but I don't think calling client.Close() like that is thread-safe?

like image 508
ronag Avatar asked Aug 13 '26 08:08

ronag


1 Answers

You can use the builtin ReceiveTimeout property.

like image 180
Thorsten Dittmar Avatar answered Aug 15 '26 08:08

Thorsten Dittmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!