代码之家  ›  专栏  ›  技术社区  ›  Mr. Boy

有没有办法通知C#编译器我不想等待异步调用?[副本]

  •  2
  • Mr. Boy  · 技术社区  · 4 年前

    给定如下代码(用于测试):

                tcpListener = new TcpListener(IPAddress.Any, port);
                tcpListener.Start();
                while (!cancellation.IsCancellationRequested)
                {
                    var client = await tcpListener.AcceptTcpClientAsync();
                    //Monitor services TCP messages to this client
                    var monitor = new Monitor(client);
                    monitor.MonitorAsync(cancellation.Token);
                }
    

    我明确表示 await MonitorAsync 因为我希望每个监视器并行运行,但是Visual Studio警告我(当然是正确的)代码执行将继续,而无需等待 监视器异步 完成。

    我更喜欢避免编译器警告,并将其视为我做错了事/不明智的迹象。那么,是否有一种“正确”的方法来做到这一点,以满足编译器的意图行为呢?

    1 回复  |  直到 4 年前
        1
  •  2
  •   Mr. Boy    4 年前

    只需分配任务并使用忽略它 discard operator :

    _ = monitor.MonitorAsync(cancellation.Token);