我有一个场景,我有多个线程添加到队列和多个线程从同一队列读取.如果队列达到特定大小,则填充队列的所有线程将在添加时被阻止,直到从队列中删除项目为止.
下面的解决方案就是我现在正在使用的问题,我的问题是:如何改进?是否有一个对象已经在我应该使用的BCL中启用此行为?
internal class BlockingCollection<T> : CollectionBase, IEnumerable
{
//todo: might be worth changing this into a proper QUEUE
private AutoResetEvent _FullEvent = new AutoResetEvent(false);
internal T this[int i]
{
get { return (T) List[i]; }
}
private int _MaxSize;
internal int MaxSize
{
get { return _MaxSize; }
set
{
_MaxSize = value;
checkSize();
}
}
internal BlockingCollection(int maxSize)
{
MaxSize = maxSize;
}
internal void Add(T item)
{
Trace.WriteLine(string.Format("BlockingCollection add waiting: {0}", Thread.CurrentThread.ManagedThreadId));
_FullEvent.WaitOne();
List.Add(item);
Trace.WriteLine(string.Format("BlockingCollection …Run Code Online (Sandbox Code Playgroud) 如何使用事件和代理在C#中实现Producer/Consumer模式?在使用这些设计模式时,我需要注意什么?我需要注意哪些边缘情况?
我有一个Sql查询,它返回我超过50万行进行处理...这个过程不需要很长时间,但我想通过一些多处理来加快它的速度.考虑到下面的代码,是否有可能轻松地多线程?
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// ...process row
}
}
Run Code Online (Sandbox Code Playgroud)
如果我可以简单地在结果列表的开头和中间获得光标,那将是完美的.这样,我可以有两个线程处理记录.但是SqlDataReader不允许我这样做......
知道如何实现这一目标吗?