2

If I have a method that can be awaited, but usually isn't, how can I prevent warnings for that method when it isn't? Attaching #pragmas to suppress at each call site is even more of an eyesore, and I don't want to disable the warning globally because many Task returning functions really should be awaited; it's just a small subset for which I want to say "Even though it can, this function doesn't expect to be awaited, so don't warn if it is called without await".

Rollie
  • 4,391
  • 3
  • 33
  • 55
  • Possible duplicate of [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) – Stefan Aug 27 '18 at 00:11
  • @Stefan I'm specifically asking how to modify the *called* method to suppress the warning; not the *calling* method. – Rollie Aug 27 '18 at 00:15
  • Wouldn't it be up to the caller to determine if the call needs to be awaited? – Stefan Aug 27 '18 at 00:24
  • 1
    The callee knows whether the contents of its operation make sense to be run without an `await`. Regardless of that, I didn't ask for code review, but rather whether a certain operation is possible or not. I think no, and if you have some credible source to answer the question in such a way, it will be appreciated. That said, it's quite rude to say "what you are trying to do is wrong, so it doesn't matter if you can do it". – Rollie Aug 27 '18 at 00:30

1 Answers1

3

It seems like you want to fire and forget certain tasks.

I wrote an extension method like:

public static class TaskExtensions
{
  public void FireAndForget(this Task task)
  {
    // access exception (and ideally log it) to avoid a potential exception being rethrown by the finalizer as an unobserved exception
    task.ContinueWith(t => Debug.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
  }
}

Now you can just mark tasks as fire-and-forget via

task.FireAndForget();

and the compiler will not complain because the task is not awaited and there will be no UnobservedTaskException occurring seemingly out of nowhere as they will be rethrown whenever the GC's finalizer thread decides to free the task making them seem somewhat erratic.

ckuri
  • 3,784
  • 2
  • 15
  • 17
  • @Stefan You are right. This is somewhat awkward and embarrassing for not looking at your link before. Should I delete my answer to avoid duplicates? – ckuri Aug 27 '18 at 00:34
  • Not sure... if you receive a lot of down-votes you'll know ;-) – Stefan Aug 27 '18 at 00:36