我的软件处理来自不同聊天的收到的消息。我想:
这就是我提出的:
public class PullUpdates
{
private ConcurrentDictionary<string, ConcurrentQueue<Message>> chatsDictionary;
private List<Task> tasks = new List<Task>();
// start pulling for ever
public async void Start()
{
while (!stopPulling)
{
var messages = await api.GetMessages(); // it will return 100 messages
foreach (var message in messages)
{
var queue = chatsDictionary.GetOrAdd(message.ChatId, x => new ConcurrentQueue<Message>());
queue.Enqueue(message);
}
tasks.Add(Task.Run(() =>
{
// process chats in parallel
Parallel.ForEach(chatsDictionary, async (dictionaryItem) =>
{
// process messages of each chat sequentially
foreach (var message in dictionaryItem.Value)
{
await ParseMessageAsync(message);
}
});
}));
// remove previous tasks that are completed now
tasks.RemoveAll(x => x.IsCompleted);
}
// wait for remaining tasks before exiting
await Task.WhenAll(tasks);
}
}
它会提取一批消息,创建一个新任务来并行处理聊天,并按顺序解析消息并继续同时拉动。
它有两个主要问题,我不知道如何解决它们。
它不断添加新任务而不考虑系统是否具有容量。
它会不断提取消息并将其添加到chatsDictionary
,同时Parallel.ForEach()
处理集合。