2楼的! using System; using System.Collections.Generic; using System.Text;namespace ThreadDemo { public class BaseCollection<T> : List<T> { protected readonly object _lockObj = new object(); private int index = 0; public virtual T GetNext() { T result = default(T); if (this.Count > 0 && index < Count) { lock (_lockObj) { result = this[index]; index++; } } return result; } public new void Add(T item) { lock (_lockObj) { base.Add(item); } } public new void Clear() { lock (_lockObj) { index = 0;
using System;
using System.Collections.Generic;
using System.Text;namespace ThreadDemo
{
public class BaseCollection<T> : List<T>
{
protected readonly object _lockObj = new object(); private int index = 0;
public virtual T GetNext()
{
T result = default(T);
if (this.Count > 0 && index < Count)
{
lock (_lockObj)
{
result = this[index];
index++;
}
}
return result;
} public new void Add(T item)
{
lock (_lockObj)
{
base.Add(item);
}
}
public new void Clear()
{
lock (_lockObj)
{
index = 0;
base.Clear();
}
}
}
}里面已经带锁了啊!
{
try
{
while (_isRun)
{
Express express = _list.GetNext();//包装过的list<T>泛型集合,做队列用!此方法是取下一个任务
if (express != null)
{
int result = express.A + express.B;
OnExpressComputed(result, express);//一个任务完成事件通知
Thread.Sleep(1000);
}
else
{
Thread.Sleep(1000);//暂停1秒,给别的线程点时间 }
}
}
catch (ThreadAbortException)
{
Thread.ResetAbort();
return;
}
catch (Exception)
{
//记录日志
}
}
加了一个else语句! Thread.Sleep(1000);//暂停1秒,给别的线程点时间这样线程就永远的干活了!不用死了!除非我让他死!啊哈哈!不知道算不算好办法!还有个问题我一直想不清楚! catch (ThreadAbortException)
{
Thread.ResetAbort();
return;
}
线程执行完任务,会自动被系统回收!系统回收也会出发ThreadAbortException这个异常吗?不是只有调用
Thread.Abort()才会出发这个异常吗?而这里又Thread.ResetAbort();取消强制关闭线程!这不是矛盾吗?乱套啊!这是我个人理解的!
要自己做的话可以参考 生产者-消费者 模式.
所以,必须要有else分支,必须要让它在没有任务时Sleep。至于后面那个catch,你写这个,是出于什么目的?