System.Timers.timer window服务 如何单线程计时???

pyez1158 2012-03-25 08:25:20
System.Timers.timer 这个会引发多线程并发,我需要它监督某某时间发邮件,它发了n份,如何控制这个Timer多线程????
...全文
277 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
pyez1158 2012-04-03
  • 打赏
  • 举报
回复
感谢楼上,有用!
mngzilin 2012-03-27
  • 打赏
  • 举报
回复
这是个演示的例子,多线程定时循环向queue中添加消息,timer定时从queue取出消息。

        static void Main(string[] args)
{
List<Thread> threadlist = new List<Thread>();
for (int i = 0; i < 5; i++)
{
Thread th = new Thread(new ParameterizedThreadStart(Func));
threadlist.Add(th);
}
isStop = false;
for (int i = 0; i < threadlist.Count; i++)
{
threadlist[i].Start(i);
Console.WriteLine("线程"+i.ToString()+"已经启动...");
}
Timer timer = new Timer(new TimerCallback(timerFun),null,0,1000);


}
static bool isStop = true;
static Queue<string> queue = new Queue<string>();
static void Func(object obj)
{
int index = (int)obj;

while (!isStop)
{
lock (queue)
{
queue.Enqueue("现在时间" + DateTime.Now.ToString());
}
Thread.Sleep(1000);
}
}

static void timerFun(object obj)
{
lock (queue)
{
if (queue.Count > 0)
{
string s = queue.Dequeue();
Console.WriteLine("取出消息:" + s);
}
}
}
pyez1158 2012-03-27
  • 打赏
  • 举报
回复
楼上能给我个例子吗,可以发一份邮件给我吗,我的邮箱是:pyez1158@163.com,万分感谢!!!
mngzilin 2012-03-26
  • 打赏
  • 举报
回复
找一个队列Queue,在多线程中每发送一次邮件就lock然后向queue中enqueue加入一条消息,然后timer定时lock后,dequeue这个队列
冰镇宝贝321 2012-03-26
  • 打赏
  • 举报
回复
可以写个demo试试下的 时间是检验真理的唯一标准
kkgoose 2012-03-26
  • 打赏
  • 举报
回复
了解下
jetable 2012-03-25
  • 打赏
  • 举报
回复
那就自己写单线程或者某一时间只能单线程访问的事件加锁

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧