How to fix the 'FileSystemException: An async operation is currently pending'?

Viewed 1970

I wrote a torrent download demo , look like this:

var peers....

for(var i =0;i < length;i++){
   var peer = peers[i];
   peer.start((List<int> data){
      _downloadFile.write(begin,end,data);
   });
}

I mean that there are mutiple peer try to access the _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);
       ....
   }

And it will throw exception : FileSystemException: An async operation is currently pending I think the reason is that different fork invoke setPosition, so I try to make each fork to wait the write operation over:

`_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();
       ....
   }

If I understand correctly, when peer recieves data , it will call write method , then it should wait the _lock completed, but I still get FileSystemException.

Now I have to use Stream , with its pause and resume method to avoid this exception.

Can someone tell me what's the problems with the last codes? why the _lock does not work? Does Dart have something like 'object lock'?

Thanks very much!

0 Answers
Related