0

I am logging each request in my asp.net core 2.2 web api. I am posting the Log to external server by spinning Task.Run method for Fire and Forget. But its throwing exception and affecting the main thread. Is there any way to Fire and Forget in asp.net core web api ?

Thanks, Subbiah K

user3141198
  • 33
  • 1
  • 7

1 Answers1

0

If your log method is an async method like this:

public async Task SendLog(Log mylog)
{
    // some async logic.
}

You can simply call it with:

SendLog(log).ConfigureAwait(false);

The send process will continue and will not block your current thread.

Reference: https://stackoverflow.com/a/53184241/8676371


But if you want to handle the exception asynchronously, you could do:

  SendLog(log).
    ContinueWith(t => Console.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted);

This will allow you to deal with an exception on a thread other than the "main" thread. This means you don't have to "wait" for the call SendLog() from the original thread; but, still allows you to do something with an exception--but only if an exception occurs.

Reference: https://stackoverflow.com/a/15524271/8676371

Anduin Xue
  • 3,266
  • 2
  • 22
  • 43
  • But what i read was, configureAwait(false) is only fr UI threads. It wont work on Asp.net – user3141198 Nov 08 '19 at 16:18
  • It works to help not await the current thread. Any platform is supported. Try it. – Anduin Xue Nov 08 '19 at 16:26
  • @user3141198 ASP.NET Core in particular doesn't use `SynchronizationContext`, so `ConfigureAwait` has no effect. However, that doesn't mean you can't use it, and I'd argue it's in fact better to always use it when you can, as if you refactor this code and use it some place else that's not ASP.NET Core, then it will very much matter. – Chris Pratt Nov 12 '19 at 14:10