public Task <bool> RemoveAsync(CacheId id, CancellationToken cancellationToken = default) { var path = IdToString(id); if (id.IsCategory) { try { Directory.Delete(path, true); return(Task.FromResult(true)); } catch (IOException) { return(Task.FromResult(false)); } } else { try { File.Delete(path); return(Task.FromResult(true)); } catch (IOException) { // noop return(Task.FromResult(false)); } } }
public async Task <T> GetOrCreateAsync <T>(CacheId id, Func <Task <T> > generator, CancellationToken cancellationToken = default) { var retries = new RetryHelper(1, 500, totalMaxDelay: Timeout); do { if (await StorageProvider.TryOpenRead(id, cancellationToken) is Stream readStream) { // Read from stream using (readStream) return(await SerializationProvider.DeserializeFromStreamAsync <T>(readStream, cancellationToken)); } else if (await StorageProvider.TryOpenWrite(id, cancellationToken) is StreamWithCompletion writeStream) { var data = await generator().ConfigureAwait(false); // Write to stream using (writeStream) await SerializationProvider.SerializeToStreamAsync(data, writeStream, cancellationToken); await writeStream; return(data); } if (await retries.DelayAsync(cancellationToken).ConfigureAwait(false) == false) { throw new TimeoutException(); } }while (!cancellationToken.IsCancellationRequested); throw new TaskCanceledException(); }
public Task <Stream?> TryOpenRead(CacheId id, CancellationToken cancellationToken = default) { var path = IdToString(id); EnsureDirectory(path); try { var result = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); return(Task.FromResult <Stream?>(result)); } catch (FileNotFoundException) { return(Task.FromResult <Stream?>(default));
public async Task <T> GetAsync <T>(CacheId id, CancellationToken cancellationToken = default) { var retries = new RetryHelper(1, 500, totalMaxDelay: Timeout); do { if (await StorageProvider.TryOpenRead(id, cancellationToken) is Stream stream) { // Read from stream using (stream) return(await SerializationProvider.DeserializeFromStreamAsync <T>(stream, cancellationToken)); } if (await retries.DelayAsync(cancellationToken).ConfigureAwait(false) == false) { throw new TimeoutException(); } }while (!cancellationToken.IsCancellationRequested); throw new TaskCanceledException(); }
protected string IdToString(CacheId id) => Path.Combine(Root, id.IsCategory ? id.ToString() : $"{id}.dat");
public Task InvalidateAsync(CacheId id, CancellationToken cancellationToken = default) => StorageProvider.RemoveAsync(id, cancellationToken);