我现在得到的是一个每 5000 毫秒触发一次的计时器:
static Timer _aTimer = new System.Timers.Timer();
static void Main(string[] args)
{
_aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
_aTimer.Interval = 5000;
_aTimer.Enabled = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
着火时,它会设置处理文件的队列:
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// stop the timer so we dont reprocess files we already have in the queue
StopTimer();
// setup a list of queues
var lists = new List<IncomingOrderQueue>();
//get the accounts in which the files we are looking in
var accounts = new List<string>() { "Account1", "Account2" };
//loop through the accounts and set up the queue
foreach (var acc in accounts)
{
// create the queue
var tmp = new IncomingOrderQueue();
// for each file in the folders add it to be processed in the queue
foreach (var orderFile in OrderFiles(acc))
{
tmp.EnqueueSweep(new QueueVariables() { Account = acc, File = orderFile });
}
// add the queue to the list of queues
lists.Add(tmp);
}
// for each of the queues consume all the contents of them
Parallel.ForEach(lists, l => l.Consume());
//start the timer back up again because we have finished all the files we have in the current queue
StartTimer();
}
public static void StopTimer()
{
Console.WriteLine("Stop Timer");
_aTimer.Stop();
_aTimer.Enabled = false;
}
public static void StartTimer()
{
Console.WriteLine("Start Timer");
_aTimer.Enabled = true;
_aTimer.Start();
}
阻塞队列本身:
public class IncomingOrderQueue
{
BlockingCollection<QueueVariables> _orderQ = new BlockingCollection<QueueVariables>();
public void EnqueueSweep(QueueVariables incoming)
{
// add items to the queue
_orderQ.Add(incoming);
}
public void Consume()
{
// stop anything been adding to the queue
_orderQ.CompleteAdding();
// consume all the objects in the blocking collection
Parallel.ForEach(_orderQ.GetConsumingEnumerable(), Processor.Order.Object);
}
public int QueueCount
{
get
{
return _orderQ.Count;
}
}
}
我所拥有的工作方式是,启动计时器->停止计时器->触发收集文件夹中所有文件的过程->处理所有文件->重新启动计时器。
我不禁认为有更好的方法来做我正在做的事情,特别是当将为帐户创建的队列数量为 200 - 400 时。
谢谢