有一堆项目不断添加到数据库中,需要处理。我希望并行处理不相似的项目。
例如:
A 类物品:第 1 项、第 2 项、第 3 项
B 类项目:第 4 项、第 5 项、第 6 项
C 类项目:第 7 项、第 8 项、第 9 项
第 1 项、第 4 项和第 7 项应并行处理。
随着越来越多的某个类型的项目被添加到数据库中,它们将被选中并排队等待处理,只有在处理完该类型的先前项目之后。
我想我可以使用带有 CustomTaskScheduler 的静态任务工厂来做到这一点,它只会在该类型的上一个任务完成后才开始一个新任务?我的问题是我的 CustomTaskScheduler 应该如何看?
class test
{
private static void Main()
{
//List of items from the database
var itemList = new List<Item>();
itemList.Add(new Item(1, "A"));
itemList.Add(new Item(2, "A"));
itemList.Add(new Item(3, "A"));
itemList.Add(new Item(4, "B"));
itemList.Add(new Item(5, "B"));
itemList.Add(new Item(6, "B"));
itemList.Add(new Item(7, "C"));
itemList.Add(new Item(8, "C"));
itemList.Add(new Item(9, "C"));
//This needs to be run on a timer picking up new items from the database every time
new ProcessQueue().ProcessAllItems(itemList);
Console.ReadLine();
}
}
public class ProcessQueue
{
private static CustomTaskScheduler customTaskScheduler = new CustomTaskScheduler(1);
private static TaskFactory factory = new TaskFactory(customTaskScheduler);
public void ProcessAllItems(List<Item> itemList)
{
var cts = new CancellationTokenSource();
foreach (var item in itemList)
{
factory.StartNew(
o =>
executeTask(item.Id, item.ItemType),
item.ItemType, //unique identifier for multiple threads
cts.Token);
}
}
public void executeTask(int id, string parentId)
{
Console.WriteLine("Item - {0} ItemType - {1} on thread {1} ", id, parentId,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(5000);
}
}
public class Item
{
public Item(int id, string itemType)
{
Id = id;
ItemType = itemType;
}
public int Id { get; set; }
public string ItemType { get; set; }
}