再你们得到源码之前,我先做个广告:张家港杰德机械/张家港三兴华轩机械是我一朋友的公司,希望需要做净水,灌装机,拔盖机,封口机,传送带等的朋友光顾。

张家港杰德机械有限公司:http://www.jiedejx.com

张家港三兴华轩机械厂:http://huaxuancch.com

OK ,开始卖包子

本程序用到队列,定时器,很简单,没什么好说的,因为用得到,所以作个记录:

如下:

    class Program
{
/// <summary>
/// 本篇示例 讲解C#队列 入队 和 定时出队,例如:早上排队买包子 设置为每隔五秒,买包子成功排队的人出队!
/// </summary>
/// <param name="args">@陈卧龙 张家港杰德机械、张家港华轩机械:http://www.huaxuancch.com http://www.jiedejx.com </param> /// <summary>
/// 全局队列
/// </summary>
public static ConcurrentQueue<Person> _ConcurrenPersons = new ConcurrentQueue<Person>();
static void Main(string[] args)
{
//模拟入队
Person model1 = new Person("宋江", "男", );
Person model2 = new Person("李逵", "男", );
Person model3 = new Person("顾大嫂", "女", );
Person model4 = new Person("扈三娘", "女", );
Person model5 = new Person("一丈青", "女", );
Person model6 = new Person("林冲", "男", );
Person model7 = new Person("武松", "男", );
Person model8 = new Person("花和尚", "男", );
List<Person> listPerson = new List<Person>();
listPerson.Add(model1);
listPerson.Add(model2);
listPerson.Add(model3);
listPerson.Add(model4);
listPerson.Add(model5);
listPerson.Add(model6);
listPerson.Add(model7);
listPerson.Add(model8);
foreach (var item in listPerson)
{
//开始排队
PersonEnqueue(item);
}
//排队完成
//
//注册Timer 在web项目中可以在 ApplicationStart 或者 静态构造函数中注册
Time_Task.Instance().ExecuteTask += new System.Timers.ElapsedEventHandler(ExecuteTask);
Time_Task.Instance().Interval = * ;//表示间隔 5秒钟执行一次
Time_Task.Instance().Start();
//
Console.WriteLine("店小二:都别吵,都别吵,再等五秒钟开始卖包子。5 4 3 2 1 ...");
Console.ReadKey();
} /// <summary>
/// 入队
/// </summary>
public static void PersonEnqueue(Person Model)
{
_ConcurrenPersons.Enqueue(Model);
} /// <summary>
/// 定时执行出队操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void ExecuteTask(object sender, System.Timers.ElapsedEventArgs e)
{
PersonDequeue();
} /// <summary>
/// 出队
/// </summary>
public static void PersonDequeue()
{
if (_ConcurrenPersons.Count > )
{
bool dequeueSuccesful = false;
bool peekSuccesful = false;
Person workItem; peekSuccesful = _ConcurrenPersons.TryPeek(out workItem); if (peekSuccesful)
{
dequeueSuccesful = _ConcurrenPersons.TryDequeue(out workItem);//出队
Console.WriteLine("大家好,我叫" + workItem.uName + ",今年" + workItem.uAge + "岁,一大早的就叫老子排队买包子,总算买完了!" + " " + DateTime.Now);
}
}
else
{
Console.WriteLine("队列里没人了............");
}
}
} public class Time_Task
{
public event System.Timers.ElapsedEventHandler ExecuteTask; private static readonly Time_Task _task = null;
private System.Timers.Timer _timer = null; //定义时间
private int _interval = *;
public int Interval
{
set
{
_interval = value;
}
get
{
return _interval;
}
} static Time_Task()
{
_task = new Time_Task();
} public static Time_Task Instance()
{
return _task;
} //开始
public void Start()
{
if (_timer == null)
{
_timer = new System.Timers.Timer(_interval);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true;
_timer.Start();
}
} protected void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (null != ExecuteTask)
{
ExecuteTask(sender, e);
}
} //停止
public void Stop()
{
if (_timer != null)
{
_timer.Stop();
_timer.Dispose();
_timer = null;
}
} } /// <summary>
/// 排队的人实体
/// </summary>
public class Person
{
public Person(string N,string S,int A)
{
uName = N;
uSex = S;
uAge = A;
}
public string uName { get; set; }
public string uSex { get; set; }
public int uAge { get; set; }
}

@陈卧龙的博客

未完持续......

如果我们换种思路,定时器一秒钟执行一次,但,每次卖包子用时还是五秒,我们应当怎么办?这样修改的好处时,用户来了,就可以直接买包子,而不用多等五秒,同理,这一波买包子的人走了后,后续来的人也不需要多等待这个五秒!

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace Test2
{
class Program
{
/// <summary>
/// 本篇示例 讲解C#队列 入队 和 定时出队,例如:早上排队买包子 设置为每隔五秒,买包子成功排队的人出队!
/// </summary>
/// <param name="args">@陈卧龙 张家港杰德机械、张家港华轩机械:http://www.huaxuancch.com http://www.jiedejx.com </param> /// <summary>
/// 全局队列
/// </summary>
public static ConcurrentQueue<Person> _ConcurrenPersons = new ConcurrentQueue<Person>(); static Program()
{
Time_Task.Instance().ExecuteTask += new System.Timers.ElapsedEventHandler(ExecuteTask);
Time_Task.Instance().Interval = * ;//修改成每隔一秒执行一次
Time_Task.Instance().Start();
}
static void Main(string[] args)
{
Console.WriteLine("店小二:都别吵,都别吵,现在马上开始卖包子 ...");
//模拟入队
Person model1 = new Person("宋江", "男", );
Person model2 = new Person("李逵", "男", );
Person model3 = new Person("顾大嫂", "女", );
Person model4 = new Person("扈三娘", "女", );
Person model5 = new Person("一丈青", "女", );
Person model6 = new Person("林冲", "男", );
Person model7 = new Person("武松", "男", );
Person model8 = new Person("花和尚", "男", );
List<Person> listPerson = new List<Person>();
listPerson.Add(model1);
listPerson.Add(model2);
listPerson.Add(model3);
listPerson.Add(model4);
listPerson.Add(model5);
listPerson.Add(model6);
listPerson.Add(model7);
listPerson.Add(model8);
foreach (var item in listPerson)
{
//开始排队
PersonEnqueue(item);
}
//排队完成 Console.ReadKey();
} /// <summary>
/// 入队
/// </summary>
public static void PersonEnqueue(Person Model)
{
_ConcurrenPersons.Enqueue(Model);
} /// <summary>
/// 定时执行出队操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void ExecuteTask(object sender, System.Timers.ElapsedEventArgs e)
{
PersonDequeue();
} /// <summary>
/// 出队
/// </summary>
public static void PersonDequeue()
{
if (_ConcurrenPersons.Count > )
{
bool dequeueSuccesful = false;
bool peekSuccesful = false;
Person workItem;
Time_Task.Instance().Stop();
peekSuccesful = _ConcurrenPersons.TryPeek(out workItem); if (peekSuccesful)
{
Console.WriteLine("大家好,我叫" + workItem.uName + ",今年" + workItem.uAge + "岁,一大早的就叫老子排队买包子,总算买完了!" + " " + DateTime.Now);
Thread.Sleep();
dequeueSuccesful = _ConcurrenPersons.TryDequeue(out workItem);//出队
}
Time_Task.Instance().Start();
}
else
{
Console.WriteLine("队列里没人了,我要关闭定时器啦............");
Time_Task.Instance().Stop();
}
}
} public class Time_Task
{
public event System.Timers.ElapsedEventHandler ExecuteTask; private static readonly Time_Task _task = null;
private System.Timers.Timer _timer = null; //定义时间
private int _interval = *;
public int Interval
{
set
{
_interval = value;
}
get
{
return _interval;
}
} static Time_Task()
{
_task = new Time_Task();
} public static Time_Task Instance()
{
return _task;
} //开始
public void Start()
{
if (_timer == null)
{
_timer = new System.Timers.Timer(_interval);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true;
_timer.Start();
}
} protected void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (null != ExecuteTask)
{
ExecuteTask(sender, e);
}
} //停止
public void Stop()
{
if (_timer != null)
{
_timer.Stop();
_timer.Dispose();
_timer = null;
}
} } /// <summary>
/// 排队的人实体
/// </summary>
public class Person
{
public Person(string N,string S,int A)
{
uName = N;
uSex = S;
uAge = A;
}
public string uName { get; set; }
public string uSex { get; set; }
public int uAge { get; set; }
}
}

案例2,如下:又来了一波买包子的人,

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace Test2
{
class Program
{
/// <summary>
/// 本篇示例 讲解C#队列 入队 和 定时出队,例如:早上排队买包子 设置为每隔五秒,买包子成功排队的人出队!
/// </summary>
/// <param name="args">@陈卧龙 张家港杰德机械、张家港华轩机械:http://www.huaxuancch.com http://www.jiedejx.com </param> /// <summary>
/// 全局队列
/// </summary>
public static ConcurrentQueue<Person> _ConcurrenPersons = new ConcurrentQueue<Person>(); static Program()
{
Time_Task.Instance().ExecuteTask += new System.Timers.ElapsedEventHandler(ExecuteTask);
Time_Task.Instance().Interval = * ;//修改成每隔一秒执行一次
Time_Task.Instance().Start();
}
static void Main(string[] args)
{
Console.WriteLine("店小二:都别吵,都别吵,现在马上开始卖包子 ...");
//模拟入队
Person model1 = new Person("宋江", "男", );
Person model2 = new Person("李逵", "男", );
List<Person> listPerson = new List<Person>();
listPerson.Add(model1);
listPerson.Add(model2);
foreach (var item in listPerson)
{
//开始排队
PersonEnqueue(item);
}
//排队完成
Thread.Sleep();
AginEnque();// 又来了一波买包子的人
Console.ReadKey();
} /// <summary>
/// 又来了一波买包子的人
/// </summary>
public static void AginEnque()
{
Console.WriteLine("又有一波买包子的人来了......");
List<Person> listPerson = new List<Person>();
listPerson.Clear();
Person model1 = new Person("刘备", "男", );
Person model2 = new Person("关羽", "男", );
Person model3 = new Person("张飞", "男", );
listPerson.Add(model1);
listPerson.Add(model2);
listPerson.Add(model3);
foreach (var item in listPerson)
{
//第二次开始排队
PersonEnqueue(item);
}
Time_Task.Instance().Start();
} /// <summary>
/// 入队
/// </summary>
public static void PersonEnqueue(Person Model)
{
_ConcurrenPersons.Enqueue(Model);
} /// <summary>
/// 定时执行出队操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void ExecuteTask(object sender, System.Timers.ElapsedEventArgs e)
{
PersonDequeue();
} /// <summary>
/// 出队
/// </summary>
public static void PersonDequeue()
{
if (_ConcurrenPersons.Count > )
{
bool dequeueSuccesful = false;
bool peekSuccesful = false;
Person workItem;
Time_Task.Instance().Stop();
peekSuccesful = _ConcurrenPersons.TryPeek(out workItem); if (peekSuccesful)
{
Console.WriteLine("大家好,我叫" + workItem.uName + ",今年" + workItem.uAge + "岁,一大早的就叫老子排队买包子,总算买完了!" + " " + DateTime.Now);
Thread.Sleep();
dequeueSuccesful = _ConcurrenPersons.TryDequeue(out workItem);//出队
}
Time_Task.Instance().Start();
}
else
{
Console.WriteLine("队列里没人了,我要关闭定时器啦............");
Time_Task.Instance().Stop();
}
}
} public class Time_Task
{
public event System.Timers.ElapsedEventHandler ExecuteTask; private static readonly Time_Task _task = null;
private System.Timers.Timer _timer = null; //定义时间
private int _interval = *;
public int Interval
{
set
{
_interval = value;
}
get
{
return _interval;
}
} static Time_Task()
{
_task = new Time_Task();
} public static Time_Task Instance()
{
return _task;
} //开始
public void Start()
{
if (_timer == null)
{
_timer = new System.Timers.Timer(_interval);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true;
_timer.Start();
}
} protected void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (null != ExecuteTask)
{
ExecuteTask(sender, e);
}
} //停止
public void Stop()
{
if (_timer != null)
{
_timer.Stop();
_timer.Dispose();
_timer = null;
}
} } /// <summary>
/// 排队的人实体
/// </summary>
public class Person
{
public Person(string N,string S,int A)
{
uName = N;
uSex = S;
uAge = A;
}
public string uName { get; set; }
public string uSex { get; set; }
public int uAge { get; set; }
}
}

未完持续...

如果我们不使用定时器,该怎么写呢?

不使用定时器时,我们可以使用C#的信号量机制,所谓信号量机制请参考鄙人写的博客:C#深入理解AutoResetEvent和ManualResetEvent 。

具体怎么实现,看下面代码:

    class Program
{
/// <summary>
/// 本篇示例 讲解C#队列 入队 和 定时出队,例如:早上排队买包子 设置为每隔五秒,买包子成功排队的人出队!
/// </summary>
/// <param name="args">@陈卧龙 张家港杰德机械、张家港华轩机械:http://www.huaxuancch.com http://www.jiedejx.com </param> /// <summary>
/// 全局队列
/// </summary>
public static ConcurrentQueue<Person> _ConcurrenPersons = new ConcurrentQueue<Person>();
static AutoResetEvent myResetEvent = new AutoResetEvent(false);
static void Main(string[] args)
{
Console.WriteLine("店小二:都别吵,都别吵,再等五秒钟开始卖包子。5 4 3 2 1 ...");
Thread thread = new Thread(PersonDequeue);
thread.Name = "queue";
thread.Start();
//模拟入队
Person model1 = new Person("宋江", "男", );
Person model2 = new Person("李逵", "男", ); List<Person> listPerson = new List<Person>();
listPerson.Add(model1);
listPerson.Add(model2);
foreach (var item in listPerson)
{
//开始排队
PersonEnqueue(item);
}
// Console.ReadKey();
} /// <summary>
/// 入队
/// </summary>
public static void PersonEnqueue(Person Model)
{
_ConcurrenPersons.Enqueue(Model); myResetEvent.Set();
Thread.Sleep();
} /// <summary>
/// 出队
/// </summary>
public static void PersonDequeue()
{
while (true)
{
myResetEvent.WaitOne();
if (_ConcurrenPersons.Count > )
{
bool dequeueSuccesful = false;
bool peekSuccesful = false;
Person workItem; peekSuccesful = _ConcurrenPersons.TryPeek(out workItem); if (peekSuccesful)
{
dequeueSuccesful = _ConcurrenPersons.TryDequeue(out workItem);//出队
Console.WriteLine("大家好,我叫" + workItem.uName + ",今年" + workItem.uAge + "岁,一大早的就叫老子排队买包子,总算买完了!" + " " + DateTime.Now);
}
}
else
{
Console.WriteLine("队列里没人了............"); }
}
}
} /// <summary>
/// 排队的人实体
/// </summary>
public class Person
{
public Person(string N, string S, int A)
{
uName = N;
uSex = S;
uAge = A;
}
public string uName { get; set; }
public string uSex { get; set; }
public int uAge { get; set; }
}

@陈卧龙的博客

C# 定时器和队列结合,卖包子啦,Timer、 AutoResetEvent、 ManualResetEvent的更多相关文章

  1. NodeJs之定时器与队列

    NodeJs之定时器与队列 一,介绍与需求 1.1,介绍 定时任务(node-schedule),是针对Node.js的一种灵活的cron-like和not-cron-like作业调度程序.它允许您使 ...

  2. 《Python》线程之锁、信号量、事件、条件、定时器、队列

    一.锁 线程为什么要有锁: += .-= 赋值操作数据不安全(要经过取值.计算.放回值,3部操作) pop .append 都是数据安全的(只有添加和删除,一次操作) 队列也是数据安全的 1.同步锁 ...

  3. 7-[多线程]-Event、定时器、队列、堆栈

    1.Event对象 线程的一个关键特性是每个线程都是独立运行且状态不可预测. 如果程序中的其他线程需要通过判断某个线程的状态来确定自己下一步的操作,这时线程同步问题就会变得非常棘手. 为了解决这些问题 ...

  4. python全栈开发,Day42(Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures)

    昨日内容回顾 线程 什么是线程? 线程是cpu调度的最小单位 进程是资源分配的最小单位 进程和线程是什么关系? 线程是在进程中的一个执行单位 多进程 本质上开启的这个进程里就有一个线程 多线程 单纯的 ...

  5. muduo网络库学习笔记(三)TimerQueue定时器队列

    目录 muduo网络库学习笔记(三)TimerQueue定时器队列 Linux中的时间函数 timerfd简单使用介绍 timerfd示例 muduo中对timerfd的封装 TimerQueue的结 ...

  6. C# 队列和栈 线程安全

    队列是其元素以先进先出(FIFO)的方式来处理集合,先入队的元素会先读取. 栈是和队列非常类似的另一个容器,栈和队列最大的区别是后进先出(LIFO),也可以说成先进后出. 队列在现实生活中的例子数不胜 ...

  7. Day034--Python--锁, 信号量, 事件, 队列, 生产者消费者模型, joinableQueue

    进程同步: 1. 锁 (重点)    锁通常被用来实现对共享资源的同步访问.为每一个共享资源创建一个Lock对象,当你需要访问该资源时,调用acquire方法来获取锁对象(如果其它线程已经获得了该锁, ...

  8. 多线程之----定时器TIMER

    结上一篇  多线程的简单介绍  http://www.cnblogs.com/duanxiaojun/p/6595847.html 在上一讲中我主要是对多线程学习这个系列做了一个大致的学习计划,然后对 ...

  9. 8.12 day31 进程间通信 Queue队列使用 生产者消费者模型 线程理论 创建及对象属性方法 线程互斥锁 守护线程

    进程补充 进程通信 要想实现进程间通信,可以用管道或者队列 队列比管道更好用(队列自带管道和锁) 管道和队列的共同特点:数据只有一份,取完就没了 无法重复获取用一份数据 队列特点:先进先出 堆栈特点: ...

随机推荐

  1. 安卓开发_浅谈WebView(转)

    ,有一个功能需要在APP中调用网站 百度了一下,发现需要用WebView来实现 实现方法很容易,我就不在这里写一遍了 ,直接转一下我学习的内容吧 原创作品,允许转载,转载时请务必以超链接形式标明文章  ...

  2. JavaScript按纯数字排序

      直接上代码: var arr=[ {name:"张散步",age:"23",sports:"篮球",number:"23112 ...

  3. MVP模式及性能优化

    1.base BaseActivity public abstract class BaseActivity<V,P extends BasePresenter<V>>exte ...

  4. 最全的android学习资料

    一.开发环境搭建 (已完成) 负责人:kris 状态:已完成 所整理标签为:搭建 SDK JDK NDK Eclipse ADT 模拟器 AVD 调试器(DEBUG) DDMS 测试 日志 Logca ...

  5. 安卓preview不显示的问题

    Render Problem Failed to load AppCompat ActionBar with unknown error 解决方法:将styles.xml文件中的: <resou ...

  6. DMA与cache一致性的问题

    Cache和DMA本身似乎是两个毫不相关的事物.Cache被用作CPU针对内存的缓存利用程序的空间局部性和时间局部性原理,达到较高的命中率,从而避免CPU每次都必须要与相对慢速的内存交互数据来提高数据 ...

  7. 进程间通信——LINUX

    1.编写一段程序,使用系统调用fork( )创建两个子进程,再用系统调用signal( )让父进  程捕捉键盘上来的中断信号(即按ctrl+c键),当捕捉到中断信号后,父进程用系统调用kill( )向 ...

  8. Android Studio 学习Demo内容及一些bug处理技巧 -----个人技术文档,两次冲刺总结

    实现的基本内容 1.基本界面的注册(包括转换界面,隐式,显式注册,主界面的入口注册) 2.匿名内部类实现Button按钮的监听事件,并通过Toast进行显示 3.界面切换(显式.隐式) 4.调用浏览器 ...

  9. hadoop系列 第二坑: hive hbase关联表问题

    关键词: hive创建表卡住了 创建hive和hbase关联表卡住了 其实针对这一问题在info级别的日志下是看出哪里有问题的(为什么只能在debug下才能看见呢,不太理解开发者的想法). 以调试模式 ...

  10. ES5-ES6-ES7_let关键字声明变量

    let命令的介绍 let是ECMAScript6中新增的关键字,用于声明变量.它的用法类似于var var a = 3 let b = 4 let变量的声明 let 命令的特点不允许在同一作用域下声明 ...