我写了一个torrent下载的demo,看起来像这样:
var peers....
for(var i =0;i < length;i++){
var peer = peers[i];
peer.start((List<int> data){
_downloadFile.write(begin,end,data);
});
}
我的意思是有多个peer
试图访问_file
。
`_downloadFile` code looks like this:
....
var _access = _file.open(mode:FileMode.writeOnlyAppend);
...
Future write(int begin,int end, List<int> block) async{
....
await _access.setPosition(begin);
await _access.writeFrom(block);
....
}
它会抛出异常:FileSystemException: An async operation is currently pending
我认为原因是不同的fork调用setPosition
,所以我尝试让每个fork等待写操作结束:
`_downloadFile` code look like this:
....
var _access = _file.open(mode:FileMode.writeOnlyAppend);
var _lock;
...
Future write(int begin,int end, List<int> block) async{
if(_lock != null) await _lock;
var c = Completer();
_lock = c.future;
....
await _access.setPosition(begin);
await _access.writeFrom(block);
c.complete();
....
}
如果我理解正确的话,当peer
接收到数据时,它会调用write
方法,然后它应该等待_lock
完成,但我仍然得到FileSystemException
。
现在我必须使用Stream
,以及它的pause
和resume
方法来避免这个异常。
谁能告诉我最后一个密码有什么问题吗?为什么_lock
不工作?Dart是否有类似“对象锁”的功能?
非常感谢!
1条答案
按热度按时间p1tboqfb1#
您很可能正在使用localStorage包,并遇到此问题:https://github.com/lesnitsky/flutter_localstorage/issues/56#issuecomment-800651187
如果两个操作同时写入存储在本地存储中的文件,而第一个操作还没有完成写入,则会出现问题。因为包没有安全性来避免并行访问同一存储,所以可能会发生这种情况并引发错误“”。
因为维护者不知何故没有意识到这个问题,我做了一个分叉,并自己应用更改来修复这个错误。你也可以在你的项目中使用它:-)
https://github.com/Ocell-io/flutter_localstorage