You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Cacheable.cs 2.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Threading.Tasks;
  3. namespace Discord
  4. {
  5. /// <summary>
  6. /// Contains an entity that may be cached.
  7. /// </summary>
  8. /// <typeparam name="TEntity">The type of entity that is cached</typeparam>
  9. /// <typeparam name="TId">The type of this entity's ID</typeparam>
  10. public struct Cacheable<TEntity, TId>
  11. where TEntity : IEntity<TId>
  12. where TId : IEquatable<TId>
  13. {
  14. /// <summary>
  15. /// Is this entity cached?
  16. /// </summary>
  17. public bool HasValue { get; }
  18. /// <summary>
  19. /// The ID of this entity.
  20. /// </summary>
  21. public TId Id { get; }
  22. /// <summary>
  23. /// The entity, if it could be pulled from cache.
  24. /// </summary>
  25. /// <remarks>
  26. /// This value is not guaranteed to be set; in cases where the entity cannot be pulled from cache, it is null.
  27. /// </remarks>
  28. public TEntity Value { get; }
  29. private Func<Task<TEntity>> DownloadFunc { get; }
  30. internal Cacheable(TEntity value, TId id, bool hasValue , Func<Task<TEntity>> downloadFunc)
  31. {
  32. Value = value;
  33. Id = id;
  34. HasValue = hasValue;
  35. DownloadFunc = downloadFunc;
  36. }
  37. /// <summary>
  38. /// Downloads this entity to cache.
  39. /// </summary>
  40. /// <returns>An awaitable Task containing the downloaded entity.</returns>
  41. /// <exception cref="Discord.Net.HttpException">Thrown when used from a user account.</exception>
  42. /// <exception cref="NullReferenceException">Thrown when the message is deleted.</exception>
  43. public async Task<TEntity> DownloadAsync()
  44. {
  45. return await DownloadFunc();
  46. }
  47. /// <summary>
  48. /// Returns the cached entity if it exists; otherwise downloads it.
  49. /// </summary>
  50. /// <returns>An awaitable Task containing a cached or downloaded entity.</returns>
  51. /// <exception cref="Discord.Net.HttpException">Thrown when used from a user account.</exception>
  52. /// <exception cref="NullReferenceException">Thrown when the message is deleted and is not in cache.</exception>
  53. public async Task<TEntity> GetOrDownloadAsync() => HasValue ? Value : await DownloadAsync();
  54. }
  55. }