小编rut*_*god的帖子

c# async wait 让我困惑,似乎什么也没做

编辑:更新LongTask()为使其能够await Task.Delay(2000);按我需要的方式工作,所以感谢您的回答,你们!


我试图从同步函数中调用异步函数,以使同步函数在异步函数完成之前继续运行。我不知道为什么下面的代码要等待LongTask()完成才能继续。我认为只有我这样做了才应该这样做await LongTask()。有人可以帮助我理解我所缺少的吗?

C#在这里摆弄

using System;
using System.Diagnostics;
using System.Threading.Tasks;
                    
public class Program
{
    public static void Main()
    {
        var timer = new Stopwatch();
        timer.Start();
        LongTask();
        timer.Stop();
        
        long ms = timer.ElapsedMilliseconds;

        Console.WriteLine(ms.ToString());
    }
    
    async static void LongTask()
    {
        Task.Delay(2000).Wait();
    }
}
Run Code Online (Sandbox Code Playgroud)

c# async-await

2
推荐指数
1
解决办法
2329
查看次数

C# - 为什么关闭 NetworkStream 会断开 TcpClient 的连接?

在 中C#,如果我关闭NetworkStream从 实例化的TCPClient.GetStream(),它会断开我的 TCP 客户端的连接。

以这段代码为例:

TcpClient tcpClient = new();
IPEndPoint ipEndPoint = new(IPAddress.Parse("xxx.xxx.xx.xx"), 1026);
tcpClient.Connect(ipEndPoint);

Console.WriteLine($"Before open stream: tcpClient.Connected == {tcpClient.Connected}");

NetworkStream stream = tcpClient.GetStream();
Console.WriteLine($"After get stream: tcpClient.Connected == {tcpClient.Connected}");

stream.Close();
Console.WriteLine($"After close stream: tcpClient.Connected == {tcpClient.Connected}");

tcpClient.Close();
Run Code Online (Sandbox Code Playgroud)

上面的代码给了我这个结果:

Before open stream: tcpClient.Connected == True
After get stream: tcpClient.Connected == True
After close stream: tcpClient.Connected == False
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释为什么会发生这种情况吗?或者也许(对于傻瓜)解释一下TcpClient和 它NetworkStream是如何相关的,以便这应该以这种方式工作?

.net c# tcpclient

1
推荐指数
1
解决办法
436
查看次数

标签 统计

c# ×2

.net ×1

async-await ×1

tcpclient ×1