【发布时间】:2019-12-08 15:38:21
【问题描述】:
我对@987654323@ 有一个待处理的ReadAsync 操作。
我的应用程序在确定不再可能发生通信时关闭TcpClient。在套接字上调用TcpClient.Close 会导致Exception thrown: 'System.ObjectDisposedException' in mscorlib.dll 被先前对ReadAsync() 的调用抛出。
如何避免这种异常?
最小示例:(使用 putty、nc 等打开连接进行测试)
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 取消ReadAsync()。有没有办法在不引发异常的情况下关闭与待处理的ReadAsync() 的连接?除非绝对必要,否则我不想在这里使用try/catch。
【问题讨论】:
标签: c# winforms async-await network-programming