Tej*_*ora 3 c# queue multithreading producer-consumer
我想用单个生产者和多个消费者的模式实现多文件下载.
我有: - 找到要在循环中下载的新链接的代码 - 当找到新链接时 - 它调用下载功能 - 下载功能接受源文件路径和目标文件路径并下载文件.
我想做什么 - 我想同时下载X个文件(我不知道文件的总数) - 在任何时候我都应该能够同时下载X文件 - 只要1个X文件完成下载 - 调用函数应该能够立即添加新的下载 - 然后立即下载
举例非常感谢
对于这个P/C问题,您只需要一个BlockingCollection<T>.
//shared and thread-safe
static BlockingCollection<string> queue = new BlockingCollection<string>(100);
// Producer
queue.Add(fileName); // will block when full
// Consumer
if (queue.TryTake(out fileName, timeOut)) // waits when empty
...
Run Code Online (Sandbox Code Playgroud)
你需要通过超时和CancellationTokens对它进行微调.