我有一个有趣的问题,Dart在命令行模式下运行 - 它太快了!
情况是代码必须访问网站并检索可下载的文件列表,然后下载每个文件以写入本地磁盘。
问题是每个下载操作都是异步运行的,并且下载开始失败,并出现错误,例如:SocketException:操作系统错误:信号量超时期限已过期。'和'连接在收到完整标题之前关闭'。到目前为止,我可以确定我的PC上的操作系统无法打开所有必需的连接,或者可能是Web服务器已被淹没。
我应该如何更改设计以限制同时连接的数量?
答案 0 :(得分:1)
有几个软件包可以让这很容易:
答案 1 :(得分:0)
除了建议GünterZöchbauer,我可以建议以下选项(轻量级软件信号量):
import 'dart:async';
import 'package:semaphore/semaphore.dart';
Future main() async {
var maxCount = 3;
var running = 0;
var simultaneous = 0;
var sm = new LocalSemaphore(maxCount);
var tasks = <Future>[];
for (var i = 0; i < 9; i++) {
tasks.add(new Future(() async {
try {
await sm.acquire();
running++;
if (simultaneous < running) {
simultaneous = running;
}
print("Start $i, running $running");
await _doWork(100);
running--;
print("End $i, running $running");
} finally {
sm.release();
}
}));
}
await Future.wait(tasks);
print("Max permits: $maxCount, max simultaneous runned: $simultaneous");
}
Future _doWork(int ms) {
// Simulate work
return new Future.delayed(new Duration(milliseconds: ms));
}
输出:
Start 0, running 1
Start 1, running 2
Start 2, running 3
End 0, running 2
Start 3, running 3
End 1, running 2
Start 4, running 3
End 2, running 2
Start 5, running 3
End 3, running 2
Start 6, running 3
End 4, running 2
Start 7, running 3
End 5, running 2
Start 8, running 3
End 6, running 2
End 7, running 1
End 8, running 0
Max permits: 3, max simultaneous runned: 3