DefaultQueryHandler.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Threading.Tasks;
  2. namespace Blue
  3. {
  4. /// <summary>
  5. /// 默认查询句柄类
  6. /// </summary>
  7. public class DefaultQueryHandler : IQueryHandler
  8. {
  9. /// <summary>
  10. /// 同步查询
  11. /// </summary>
  12. public R DoQuery<Q, R>() where Q : IQuery<R>, new()
  13. {
  14. return DoQuery(new Q());
  15. }
  16. /// <summary>
  17. /// 同步查询
  18. /// </summary>
  19. public R DoQuery<R>(IQuery<R> query)
  20. {
  21. return query.DoQuery();
  22. }
  23. /// <summary>
  24. /// 异步查询
  25. /// </summary>
  26. public IQueryResult<R> DoQueryAsync<R>(IQuery<R> query)
  27. {
  28. DefaultQueryResult<R> queryResult = new DefaultQueryResult<R>();
  29. var queryTask = Task.Run(() => {
  30. return query.DoQuery();
  31. });
  32. var awaiter = queryTask.GetAwaiter();
  33. awaiter.OnCompleted(() => {
  34. /*
  35. Task.IsFaulted:
  36. 获取 Task 是否由于未经处理异常的原因而完成,如果任务引发了未经处理的异常,则为 true;否则为 false
  37. Task.IsCanceled
  38. 获取此 Task 实例是否由于被取消的原因而已完成执行,如果任务由于被取消而完成,则为 true;否则为 false
  39. */
  40. if (queryTask.IsFaulted | queryTask.IsCanceled)
  41. {
  42. queryResult.TriggerFailed();
  43. }
  44. else
  45. {
  46. queryResult.TriggerSuccess(awaiter.GetResult());
  47. }
  48. });
  49. return queryResult;
  50. }
  51. /// <summary>
  52. /// 异步查询
  53. /// </summary>
  54. public IQueryResult<R> DoQueryAsync<Q, R>() where Q : IQuery<R>, new()
  55. {
  56. return DoQueryAsync(new Q());
  57. }
  58. }
  59. }