我尝试使用.NET Core并连接到本地TCP服务器。当我同步执行时没有问题 (请参见第一个
Connect
方法)。但是,当我尝试使用async
/await
执行时(请参见第二个ConnectAsync
方法),它变得非常混乱,几乎无法调试。我不确定是否正确使用TcpClient,因为网络上还没有太多的示例。确切的问题在调用TcpClient.GetStream
后开始。我尝试禁用JustMyCode
并勾选Visual Studio Code中的All exceptions
复选框进行调试,但是它不进入TcpClient.GetStream
。
async
模式下的观察结果:
- 有时会直接崩溃在
TcpClient.GetStream
中 - 有时它会在调用函数返回之后崩溃 (我有时会看到最后一个
Console.WriteLine
出现在控制台中) - 程序立即停止,调试器关闭(没有抛出异常)
- 返回代码始终为零(
The program 'bla' has exited with code 0 (0x00000000)
)
我的系统/项目设置:
- Windows 10 64位(Education)
- .NET Core 1.0.0
- 控制台应用程序
- 本地TCP服务器,因此没有连接问题
- Visual Studio Code(不应该有影响)
代码:
public class Connection
{
private TcpClient _client;
public NetworkStream Stream { get; private set; }
private CancellationTokenSource _token;
public Connection()
{
_token = new CancellationTokenSource();
_client = new TcpClient();
}
public void Connect(string host, int port)
{
Console.WriteLine("connecting...");
_client.ConnectAsync(host, port);
Console.WriteLine("connected!");
while (!_client.Connected)
{
Thread.Sleep(20);
}
Console.WriteLine("getting stream...");
Stream = _client.GetStream(); // works because of Thread.Sleep above until the socket is connected
Console.WriteLine("got stream!");
}
public async Task ConnectAsync(string host, int port)
{
Console.WriteLine("connecting...");
await _client.ConnectAsync(host, port);
Console.WriteLine("connected!");
// I know I could check for TcpClient.Connected but I see in debugger that the property is True
Console.WriteLine("getting stream...");
Stream = _client.GetStream(); // crash in GetStream / crash after this function has returned
Console.WriteLine("got stream!"); // sometimes this is going to be printed, sometimes not
}
// ...
}