[英]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 . 我正在使用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 但是我有使用.net framework 4.0的限制,我不能使用
await Task.Yield();
I understand this is the only way to make sure that the method is executed asynchronously, from Microsoft : 我了解这是确保从Microsoft异步执行该方法的唯一方法:
You can use await Task.Yield();
您可以使用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? 我的问题是:.net 4.0中此实现的替代方法是什么?
Based on @Evk message I have tried this: 基于@Evk消息,我已经尝试过了:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.