我有一个应用程序,定期启动火和忘任务,主要用于日志记录,我的问题是,当应用程序关闭时,任何当前运行的火灾和遗忘任务都会被中止。我想防止这种情况发生,所以我正在寻找一种机制,可以让我在关闭我的应用程序之前完成所有运行的火灾和遗忘操作。我不想处理他们可能的例外,我不关心这些。我只是想让他们有机会完成(可能有一个超时,但这不是问题的一部分)。
你可能会说,这一要求使我的任务没有真正地付诸东流,这是有道理的,所以我想澄清这一点:
下面是这个问题的一个最起码的例子:
static class Program
{
static async Task Main(string[] args)
{
_ = Log("Starting"); // fire and forget
await Task.Delay(1000); // Simulate the main asynchronous workload
CleanUp();
_ = Log("Finished"); // fire and forget
// Here any pending fire and forget operations should be awaited somehow
}
private static void CleanUp()
{
_ = Log("CleanUp started"); // fire and forget
Thread.Sleep(200); // Simulate some synchronous operation
_ = Log("CleanUp completed"); // fire and forget
}
private static async Task Log(string message)
{
await Task.Delay(100); // Simulate an async I/O operation required for logging
Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {message}");
}
}输出:
11:14:11.441 Starting
11:14:12.484 CleanUp started
Press any key to continue . . .不记录"CleanUp completed"和"Finished"条目,因为应用程序过早终止,挂起的任务被中止。有什么方法可以让我等待他们在结束前完成?
顺便说一句,这个问题是由@SHAFEESPS的一个最近的问题启发的,这个问题被不幸地关闭了,因为不清楚。
Clarification: --上面介绍的最小示例包含一种单一类型的触发和遗忘操作,即Task Log方法.现实世界的应用程序启动的“火与忘”操作是多个且异构的。有些甚至返回像Task<string>或Task<int>这样的通用任务。
也有可能是一个火灾和遗忘的任务可能会触发次要的射击和遗忘任务,这些应该允许开始和等待。
发布于 2020-11-07 11:12:03
一件合理的事情是在您的记录器中包含内存中的队列(这适用于与您的标准相匹配的其他类似功能),这是单独处理的。然后,您的日志方法就变成了如下所示:
private static readonly BlockingCollection<string> _queue = new BlockingCollection<string>(new ConcurrentQueue<string>());
public static void Log(string message) {
_queue.Add(message);
}它对于调用者来说是非常快速和非阻塞的,并且在某种意义上是异步的,它在将来的某个时候已经完成了(或者失败)。打电话的人不知道也不关心结果,所以这是一项任重道远的任务.
但是,这个队列被单独地、全局地、可能在一个单独的线程中处理,或者通过等待(和线程池线程)来处理(通过将日志消息插入最终目标(如文件或数据库)),这并不重要。
然后,在应用程序退出之前,您只需要通知队列处理器不再需要更多的项,并等待它完成。例如:
_queue.CompleteAdding(); // no more items
_processorThread.Join(); // if you used separate thread, otherwise some other synchronization construct.编辑:如果您希望队列处理是异步的-您可以使用这个AsyncCollection (作为nuget包可用)。然后,您的代码变成:
class Program {
private static Logger _logger;
static async Task Main(string[] args) {
_logger = new Logger();
_logger.Log("Starting"); // fire and forget
await Task.Delay(1000); // Simulate the main asynchronous workload
CleanUp();
_logger.Log("Finished"); // fire and forget
await _logger.Stop();
// Here any pending fire and forget operations should be awaited somehow
}
private static void CleanUp() {
_logger.Log("CleanUp started"); // fire and forget
Thread.Sleep(200); // Simulate some synchronous operation
_logger.Log("CleanUp completed"); // fire and forget
}
}
class Logger {
private readonly AsyncCollection<string> _queue = new AsyncCollection<string>(new ConcurrentQueue<string>());
private readonly Task _processorTask;
public Logger() {
_processorTask = Process();
}
public void Log(string message) {
// synchronous adding, you can also make it async via
// _queue.AddAsync(message); but I see no reason to
_queue.Add(message);
}
public async Task Stop() {
_queue.CompleteAdding();
await _processorTask;
}
private async Task Process() {
while (true) {
string message;
try {
message = await _queue.TakeAsync();
}
catch (InvalidOperationException) {
// throws this exception when collection is empty and CompleteAdding was called
return;
}
await Task.Delay(100);
Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {message}");
}
}
}或者您可以使用单独的专用线程来同步处理项,就像通常所做的那样。
编辑2:这是引用计数的变化,它不会对“火和忘记”任务的性质做出任何假设:
static class FireAndForgetTasks {
// start with 1, in non-signaled state
private static readonly CountdownEvent _signal = new CountdownEvent(1);
public static void AsFireAndForget(this Task task) {
// add 1 for each task
_signal.AddCount();
task.ContinueWith(x => {
if (x.Exception != null) {
// do something, task has failed, maybe log
}
// decrement 1 for each task, it cannot reach 0 and become signaled, because initial count was 1
_signal.Signal();
});
}
public static void Wait(TimeSpan? timeout = null) {
// signal once. Now event can reach zero and become signaled, when all pending tasks will finish
_signal.Signal();
// wait on signal
if (timeout != null)
_signal.Wait(timeout.Value);
else
_signal.Wait();
// dispose the signal
_signal.Dispose();
}
}你的样本变成:
static class Program {
static async Task Main(string[] args) {
Log("Starting").AsFireAndForget(); // fire and forget
await Task.Delay(1000); // Simulate the main asynchronous workload
CleanUp();
Log("Finished").AsFireAndForget(); // fire and forget
FireAndForgetTasks.Wait();
// Here any pending fire and forget operations should be awaited somehow
}
private static void CleanUp() {
Log("CleanUp started").AsFireAndForget(); // fire and forget
Thread.Sleep(200); // Simulate some synchronous operation
Log("CleanUp completed").AsFireAndForget(); // fire and forget
}
private static async Task Log(string message) {
await Task.Delay(100); // Simulate an async I/O operation required for logging
Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {message}");
}
}发布于 2020-11-07 09:46:10
也许有个柜台可以在出口等候?这还是会让人生不如死的。
我只将LogAsync移动到它自己的方法,因为每次调用日志时都不需要丢弃。我想,它还可以处理程序退出时调用Log时会发生的微小的竞赛条件。
public class Program
{
static async Task Main(string[] args)
{
Log("Starting"); // fire and forget
await Task.Delay(1000); // Simulate the main asynchronous workload
CleanUp();
Log("Finished"); // fire and forget
// Here any pending fire and forget operations should be awaited somehow
var spin = new SpinWait();
while (_backgroundTasks > 0)
{
spin.SpinOnce();
}
}
private static void CleanUp()
{
Log("CleanUp started"); // fire and forget
Thread.Sleep(200); // Simulate some synchronous operation
Log("CleanUp completed"); // fire and forget
}
private static int _backgroundTasks;
private static void Log(string message)
{
Interlocked.Increment(ref _backgroundTasks);
_ = LogAsync(message);
}
private static async Task LogAsync(string message)
{
await Task.Delay(100); // Simulate an async I/O operation required for logging
Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {message}");
Interlocked.Decrement(ref _backgroundTasks);
}
}https://stackoverflow.com/questions/64726190
复制相似问题