📄 backgroundscheduler.cs
字号:
//===============================================================================
// CSDN HeyCache
//===============================================================================
// 修改记录:[按最后修改时间倒排序]
// 2007.06.11 by tangwei
//
// 代码来源:参考于dotnet企业库3.0版
//===============================================================================
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace HeyCacher.Components.Scavenger
{
/// <summary>
/// 后台缓存回收器
/// </summary>
public class BackgroundScheduler
{
private ProducerConsumerQueue inputQueue = new ProducerConsumerQueue();
private Thread inputQueueThread;
private ExpirationTask expirer;
private bool isActive;
private bool running;
/// <summary>
/// Initialize a new instance of the <see cref="BackgroundScheduler"/> with a <see cref="ExpirationTask"/> and a <see cref="ScavengerTask"/>.
/// </summary>
/// <param name="expirer">The expiration task to use.</param>
/// <param name="scavenger">The scavenger task to use.</param>
/// <param name="instrumentationProvider">The instrumentation provider to use.</param>
public BackgroundScheduler(ExpirationTask expirer)
{
this.expirer = expirer;
ThreadStart queueReader = new ThreadStart(QueueReader);
inputQueueThread = new Thread(queueReader);
inputQueueThread.IsBackground = true;
}
/// <summary>
/// Starts the scavenger.
/// </summary>
public void Start()
{
running = true;
inputQueueThread.Start();
}
/// <summary>
/// Stops the scavenger.
/// </summary>
public void Stop()
{
running = false;
inputQueueThread.Interrupt();
}
/// <summary>
/// Determines if the scavenger is active.
/// </summary>
/// <value>
/// <see langword="true"/> if the scavenger is active; otherwise, <see langword="false"/>.
/// </value>
public bool IsActive
{
get { return isActive; }
}
/// <summary>
/// Queues a message that the expiration timeout has expired.
/// </summary>
/// <param name="notUsed">Ignored.</param>
public void ExpirationTimeoutExpired(object notUsed)
{
inputQueue.Enqueue(new ExpirationTimeoutExpiredMsg(this));
}
public void ExpirationTimeoutExpired(object notUsed, System.Timers.ElapsedEventArgs e)
{
inputQueue.Enqueue(new ExpirationTimeoutExpiredMsg(this));
}
internal void DoExpirationTimeoutExpired()
{
expirer.DoExpirations();
}
private void QueueReader()
{
isActive = true;
while (running)
{
IQueueMessage msg = inputQueue.Dequeue() as IQueueMessage;
try
{
if (msg == null)
{
continue;
}
msg.Run();
}
catch (ThreadInterruptedException ex)
{
Caches.log.Warn("回收器在逐一执行队列中每个失效判定的时候出现了一个线程错误,通常可能是所用时间太长引起的", ex);
}
catch (Exception ex)
{
Caches.log.Warn("回收器在逐一执行队列中每个失效判定的时候出现了一个未知错误,通常可能是执行失效判定引起的", ex);
}
}
isActive = false;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -