简体   繁体   中英

c# fire and forget async method: implement yield() in .net 4

I am trying to implement a fire and forget async method, to log for auditing purposes.

I am following this example Async throw-away fire-and-forget with C#.NET .

   public async Task MessageAsync(string message, DateTime date)
   {
      _logger.Info($"At {DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)}: {message}");
      await Task.Yield(); //NOT POSSIBLE IN .NET 4.0
   }

But I have the restriction to use .net framework 4.0, and I can't use

 await Task.Yield();

I understand this is the only way to make sure that the method is executed asynchronously, from Microsoft :

You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.

My question is: What is the alternative for this implementation in .net 4.0?

Based on @Evk message I have tried this:

Task MessageAsync(string message, DateTime date, CancellationToken token)
{
   var messageToLog =$"At {date.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)}: {message}";
   Task.Factory.StartNew(() => _logger.Info(messageToLog), token);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM