retryOnLock<T> function

T retryOnLock<T>(
  1. T action(), {
  2. int attempts = 6,
})

Runs action, retrying a few times with growing pauses when Windows says a file is in use (an antivirus scan, an indexer, the analyzer).

Implementation

T retryOnLock<T>(T Function() action, {int attempts = 6}) {
  for (var i = 1; ; i++) {
    try {
      return action();
    } on FileSystemException catch (e) {
      final code = e.osError?.errorCode;
      final locked = Platform.isWindows && (code == 5 || code == 32);
      if (!locked || i >= attempts) rethrow;
      sleep(Duration(milliseconds: 50 * i * i));
    }
  }
}