0

I debounce file change notifications like this:

ChangeToken.OnChange(
  () => GetReloadToken(),
  async () => await debouncer.Debounce(OnReloaded)  // <--- concern
);

There is no async overload for ChangeToken.OnChange, but hopefully there will be in v7.

That code's been working for years without error. But now I'm using a code analyser which complains that I'm using a fire-and-forget (async void), and that exceptions could crash the process - unlikely in this particular case, but I want to reevaluate anyway.

There are other ways to write that action, e.g. () => debouncer.Debounce(OnConfigReloaded).ConfigureAwait(false), but I'm unsure which is "safest" (or the one with the least problems).

So, until there's an async overload, what is the safest way to write that action?


PS, if an async overload matters to you, please upvote the issue on the repo.

lonix
  • 14,255
  • 23
  • 85
  • 176
  • What code analyzer is reporting that? What do you expect that code to do, anyway? – Paulo Morgado Jul 07 '22 at 21:46
  • @PauloMorgado The AsyncFixer analyser. It is correct, that is a "fire and forget" because it's an async void. I just want to ensure there is no safer way to write it. – lonix Jul 08 '22 at 00:00

1 Answers1

0

The problem is in an async void, exceptions will crash the process. Even though my async work has exception handling, I added more at the callsite to make it explicit and improve maintainability - unless I'm mistaken there's nothing more that can be done.

Simplify callsite:

ChangeToken.OnChange(
  () => ChangeTokenProducer(),
  async () => await ChangeTokenConsumer()   // maybe could be improved
);

And move async work into normal async method:

public async Task ChangeTokenConsumer()
{
  try {
    //...
  }
  catch (Exception e) {
    _logger.LogError(e, "Oops");
  }
}

That doesn't avoid the problem as it's still an async void. But it's clearer what's going on. And I can silence the "AsyncFixer" analyser for that one liner.

I'm still unsure whether the async syntax could be improved, but this is more maintainable than the original approach. If you have a better approach please post it and I'll accept yours.

lonix
  • 14,255
  • 23
  • 85
  • 176