【发布时间】:2015-03-15 07:17:00
【问题描述】:
我有以下代码:
class Program
{
static void Main(string[] args)
{
var watcher = new SNotifier(DumpToConsole);
watcher.StartQueue();
Console.ReadLine();
}
private static void DumpToConsole(IList<Timestamped<int>> currentCol)
{
Console.WriteLine("buffer time elapsed, current collection contents is: {0} items.", currentCol.Count);
Console.WriteLine("holder has: {0}", currentCol.Count);
}
}
SNotifier:
public class SNotifier
{
private BlockingCollection<int> _holderQueue;
private readonly Action<IList<Timestamped<int>>> _dumpAction;
public SNotifier(Action<IList<Timestamped<int>>> dumpAction)
{
PopulateListWithStartValues();
_dumpAction = dumpAction;
}
public void StartQueue()
{
PopulateQueueOnDiffThread();
var observableCollection = _holderQueue.ToObservable();
var myCollectionTimestamped = observableCollection.Timestamp();
var bufferedTimestampedCollection = myCollectionTimestamped.Buffer(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3));
using (bufferedTimestampedCollection.Subscribe(_dumpAction))
{
Console.WriteLine("started observing collection");
}
}
private void PopulateQueueOnDiffThread()
{
Action addToCollectionAction = AddToCollection;
var t = new TaskFactory();
t.StartNew(addToCollectionAction);
}
private static IEnumerable<int> GetInitialElements()
{
var random = new Random();
var items = new List<int>();
for (int i = 0; i < 10; i++)
items.Add(random.Next(1, 10));
return items;
}
private void AddToCollection()
{
while (true)
{
var newElement = new Random().Next(1, 10);
_holderQueue.Add(newElement);
Console.WriteLine("added {0}", newElement);
Console.WriteLine("holder has: {0}", _holderQueue.Count);
Thread.Sleep(1000);
}
}
private void PopulateListWithStartValues()
{
_holderQueue = new BlockingCollection<int>();
var elements = GetInitialElements();
foreach (var i in elements)
_holderQueue.Add(i);
}
}
我需要运行 DumpToConsole() 方法以每 3 秒 显示一次集合计数,而此集合的内容正在另一个线程上更改。我的问题是 DumpToConsole() 只调用一次。这是为什么?!我已经花了一整天的时间在这上面。由于我已经使用我的 dump 方法订阅了 observable,它应该“观察”集合的变化并每 3 秒重新调用 DumpToConsole() 方法;这就是我需要的。
想法?谢谢
(PS 传递给 SNotifier 类的操作是我在 SNotifier 中删除控制台相关内容的方法,我需要更好地重构它,它可以忽略,因为它与问题本身无关)
【问题讨论】:
标签: c# multithreading system.reactive observer-pattern