這對我來說聽起來非常像TPL的問題。你有一組已知的數據。您想分割一些繁重的處理並行運行,並且希望能夠批處理負載。
我沒有看到問題的任何地方是異步的源代碼,是運動數據的源代碼或需要被動的消費者。這是我建議您使用TPL的理由。
在另一個註釋中,爲什麼要並行處理10個幻數?這是業務需求,還是潛在的優化性能的嘗試?通常最好的做法是讓TaskPool根據核心數量和當前負載計算出最適合客戶端CPU的最佳實踐。我想,隨着設備及其CPU結構(單核,多核,多核,低功耗/禁用內核等)的巨大變化,這變得越來越重要。
這裏有一種方法可以做到這在LinqPad(但要注意缺乏Rx的)
void Main()
{
var source = new List<Item>();
for (int i = 0; i < 100; i++){source.Add(new Item(i));}
//Put into batches of ten, but only then pass on the item, not the temporary tuple construct.
var batches = source.Select((item, idx) =>new {item, idx})
.GroupBy(tuple=>tuple.idx/10, tuple=>tuple.item);
//Process one batch at a time (serially), but process the items of the batch in parallel (concurrently).
foreach (var batch in batches)
{
"Processing batch...".Dump();
var results = batch.AsParallel().Select (item => item.Process());
foreach (var result in results)
{
result.Dump();
}
"Processed batch.".Dump();
}
}
public class Item
{
private static readonly Random _rnd = new Random();
private readonly int _id;
public Item(int id)
{
_id = id;
}
public int Id { get {return _id;} }
public double Process()
{
var threadId = Thread.CurrentThread.ManagedThreadId;
string.Format("Processing on thread:{0}", threadId).Dump(Id);
var loopCount = _rnd.Next(10000,1000000);
Thread.SpinWait(loopCount);
return _rnd.NextDouble();
}
public override string ToString()
{
return string.Format("Item:{0}", _id);
}
}
如果你有一個數據在運動問題或反應我很想找出消費者問題,但只是「淡化」了問題,以便於解釋。
謝謝阿隆。你能解釋一下你的代碼嗎?非常感謝 – user2017793 2013-02-26 14:12:07
真的很簡單。窗口(10)將工作轉換爲塊10.合併(1)在單個線程上工作。將這10名學生轉換成一個內部可觀察的。呃,做一些工作吧。 ObserveOnDispatcher()返回到下一位的UI線程。 Do ...嗯...在UpdatingUI上工作。最後訂閱內部可觀察。沖洗並重復。 – Aron 2013-02-26 14:55:38
再次感謝阿隆。我的疑問是如何釋放每個10個學生對象資源。你的解釋非常有幫助,非常感謝。我擔心內存不足問題。請幫助我。 – user2017793 2013-02-26 15:08:15