I have a pending ReadAsync
operation on a TcpClient
.
My application closes the TcpClient
when it determines that no more communication is likely to occur. Calling TcpClient.Close
on the socket causes Exception thrown: 'System.ObjectDisposedException' in mscorlib.dll
to be thrown by the prior call to ReadAsync()
.
How can this exception be avoided?
Minimal example: (use putty, nc, etc to open a connection to test this)
using System;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Threading.Tasks;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private TcpClient client;
// Initialize the form
public Form1()
{
InitializeComponent();
}
// Start the Listen() task when the form loads
private void Form1_Load(object sender, EventArgs e)
{
var task = Listen();
}
// Listen for the connection
public async Task Listen()
{
// Start the listener
var listener = new TcpListener(IPAddress.Any, 80);
listener.Start();
// Accept a connection
client = await listener.AcceptTcpClientAsync();
// Wait for some data (the client doesn't send any for the sake of reproducing the issue)
// An exception is generated in 'ReadAsync' after Button1 is clicked
byte[] buffer = new byte[100];
await client.GetStream().ReadAsync(buffer, 0, 100);
}
// I will click this button before the above call to `ReadAsync` receives any data
private void button1_Click_1(object sender, EventArgs e)
{
// This causes an exception in the above call to `ReadAsync`
client.Close();
}
}
}
CancellationToken can't be used to cancel ReadAsync()
. Is there no way to close a connection with a pending ReadAsync()
without throwing an exception? I don't want to use try/catch
here unless absolutely necessary.