代码如下: private static object lockobj = new object();
private static List<MyPack> list = new List<MyPack>();
static System.Timers.Timer timer = null;
public static void Run()
{
timer = new System.Timers.Timer();
timer.Interval = 60000;
timer.Elapsed += new ElapsedEventHandler(
(o, e) =>
{
BeginSend(ref list);
});
timer.Enabled = true;
timer.Start();
}
public static void AppendItemToPipe(MyPack item)
{
while (!Monitor.TryEnter(lockobj))
{
Thread.Sleep(2);
}
if (item != null)
{
maillist.Add(item);
}
Monitor.Exit(lockobj);
}
private static void BeginSend(ref List<MyPack> list)
{
while (!Monitor.TryEnter(lockobj))
{
Thread.Sleep(2);
}
foreach (var single in list)
{
System.Threading.ThreadPool.QueueUserWorkItem(
o =>
{
send(single);
}
);
}
list = new List<MyPack>();
Monitor.Exit(lockobj);
}
程序启动时会运行Run()方法。
外部通过AppendItemToPipe方法添加一个对象到list<MyPack>中。
每隔1分钟执行一次BeginSend,在执行BeginSend时不允许外部通过AppendItemToPipe方法向List中添加对象。当BeginSend方法foreach执行完成后再次允许外部通过AppendItemToPipe方法向List中添加对象。上面这段代码能达到这样的预期目的吗?
private static List<MyPack> list = new List<MyPack>();
static System.Timers.Timer timer = null;
public static void Run()
{
timer = new System.Timers.Timer();
timer.Interval = 60000;
timer.Elapsed += new ElapsedEventHandler(
(o, e) =>
{
BeginSend(ref list);
});
timer.Enabled = true;
timer.Start();
}
public static void AppendItemToPipe(MyPack item)
{
while (!Monitor.TryEnter(lockobj))
{
Thread.Sleep(2);
}
if (item != null)
{
maillist.Add(item);
}
Monitor.Exit(lockobj);
}
private static void BeginSend(ref List<MyPack> list)
{
while (!Monitor.TryEnter(lockobj))
{
Thread.Sleep(2);
}
foreach (var single in list)
{
System.Threading.ThreadPool.QueueUserWorkItem(
o =>
{
send(single);
}
);
}
list = new List<MyPack>();
Monitor.Exit(lockobj);
}
程序启动时会运行Run()方法。
外部通过AppendItemToPipe方法添加一个对象到list<MyPack>中。
每隔1分钟执行一次BeginSend,在执行BeginSend时不允许外部通过AppendItemToPipe方法向List中添加对象。当BeginSend方法foreach执行完成后再次允许外部通过AppendItemToPipe方法向List中添加对象。上面这段代码能达到这样的预期目的吗?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货