0

Given code like the following (for testing):

            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);
            }

I explicitly do not want to await on MonitorAsync because I want each Monitor to run in parallel, however Visual Studio warns me (correctly of course) that code execution will continue without waiting for MonitorAsync to complete.

I prefer to avoid compiler warnings and view them as a sign I'm doing things wrong/unwisely. So is there a 'proper' way to do this which will satisfy the compiler it is intentional behaviour?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • Is the `Monitor` a custom class? If yes, be aware that there is already a [class with the same name](https://learn.microsoft.com/en-us/dotnet/api/system.threading.monitor) in the .NET platform, which could create confusion. – Theodor Zoulias Jun 30 '20 at 18:15
  • @TheodorZoulias it is, in its own namespace. Thanks for pointing this out though. – Mr. Boy Jun 30 '20 at 18:16
  • 1
    Is it an option to add a synchronous equivalent of the `MonitorAsync` method to the `Monitor` class? Because if no one is going to observe the `Task`, you may as well not create a `Task` at all. It is just dead weight and extra work for the garbage collector. The easiest way to do it is by converting the `async Task` method to `async void`. This way you'll also get the possibly desirable behavior that any exception left unhandled will crash your application, instead of leaving it running with its state potentially corrupted. – Theodor Zoulias Jun 30 '20 at 18:24
  • 1
    @TheodorZoulias interesting. I mean it's asyncronous in the sense it doesn't block, but it maybe doesn't need to be `async`. But I would like to be able to track the completion - On the wider issue I asked a separate question, in case that is a better place : https://stackoverflow.com/questions/62663752/how-should-completion-of-non-awaited-tasks-be-detected I think Sean's answer is correct for the context of this particular question, but opens up a larger question on design. – Mr. Boy Jun 30 '20 at 18:29
  • Yeap, this question in a narrow context is probably a duplicate of this: [Suppressing “warning CS4014: Because this call is not awaited, execution of the current method continues…”](https://stackoverflow.com/questions/22629951/suppressing-warning-cs4014-because-this-call-is-not-awaited-execution-of-the) – Theodor Zoulias Jun 30 '20 at 18:35

1 Answers1

2

Just assign the task and ignore it using the discard operator:

_ = monitor.MonitorAsync(cancellation.Token);
Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
Sean
  • 60,939
  • 11
  • 97
  • 136