111,080
社区成员




// 每秒钟运行下AddMsg,把数据放到Queue buffer里
System.Threading.Timer fTimer = new System.Threading.Timer(new TimerCallback(AddMsg), new AutoResetEvent(false), 0, 1000);
public void AddMsg()
{
// 你把要发送的数据msg放到Queue buffer里
}
public void SendMsg()
{
// 每次从Queue buffer里取一个数据,然后发送
while(true)
{
msg = buffer.Dequeue();
// 做你的DoTask
}
}
// 你用个Thread执行SendMsg,当你执行fTimer.Dispose()后,再加个语句把Thread停止掉
class TaskService
{
volatile bool running = true;
public void DoTask(Object stateInfo)
{
int threadsLeft, dummy;
ThreadPool.GetAvailableThreads(out threadsLeft, out dummy);
if (threadsLeft < 2) return; //<----
lock (this)
{
if (!running) return; //<----
//任务代码
}
}
public void test()
{
using (System.Threading.Timer fTimer = new Timer(new TimerCallback(DoTask), null, 0, 1000))
{
Console.ReadLine();
fTimer.Change(0, Timeout.Infinite);
running = false;
}
Console.ReadLine();
}
static void Main()
{
new TaskService().test();
}
}
volatile bool running = true;
public void DoTasks()
{
DateTime last = new DateTime();
while (running)
{
DateTime current = DateTime.Now;
int elasped = (int) (current - last).TotalMilliseconds;
last = current;
if (elasped < 1000)
{
Thread.Sleep(Math.Min(1000, 1000 - elasped));
}
//任务代码...
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Test t = new Test();
while (t.Enabled) ;
Console.WriteLine("STOPING:" + t.Value);
t.Stop();
Console.WriteLine("STOPPED:" + t.Value);
Console.ReadLine();
}
}
public class Test
{
System.Threading.Timer fTimer;
private int i = 0;
System.Timers.Timer timer;
public int Value
{
get
{
return i;
}
}
public bool Enabled
{
get
{
return timer.Enabled;
}
}
public Test()
{
fTimer = new System.Threading.Timer(new TimerCallback(this.DoTask), new AutoResetEvent(false), 0, 1000);
timer = new System.Timers.Timer(10000);
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timer.Enabled = false;
}
public void DoTask(Object stateInfo)
{
lock (this)
{
Console.WriteLine(i++);
Thread.Sleep(2000);
}
}
public void Stop()
{
fTimer.Dispose();
}
}
}