UiHelper.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. using System;
  2. using System.Threading;
  3. using Xilium.CefGlue.Helpers.Log;
  4. namespace Xilium.CefGlue.WPF
  5. {
  6. public class UiHelper : IUiHelper
  7. {
  8. private readonly ILogger _log;
  9. public UiHelper(ILogger log)
  10. {
  11. if (log == null)
  12. {
  13. throw new ArgumentNullException("log");
  14. }
  15. _log = log;
  16. }
  17. public void PerformInUiThread(Action action)
  18. {
  19. if (action == null)
  20. {
  21. throw new ArgumentNullException("action");
  22. }
  23. var currentApplication = System.Windows.Application.Current;
  24. if ((currentApplication == null) || (Thread.CurrentThread == currentApplication.Dispatcher.Thread))
  25. {
  26. action.Invoke();
  27. }
  28. else
  29. {
  30. currentApplication.Dispatcher.Invoke(action);
  31. }
  32. }
  33. public void StartAsynchronously(Action action)
  34. {
  35. if (action == null)
  36. {
  37. throw new ArgumentNullException("action");
  38. }
  39. (new Thread(action.Invoke)).Start();
  40. }
  41. public void PerformForMinimumTime(Action action, bool requiresUiThread, int minimumMillisecondsBeforeReturn)
  42. {
  43. if (action == null)
  44. {
  45. throw new ArgumentNullException("action");
  46. }
  47. var startTime = Environment.TickCount;
  48. if (requiresUiThread)
  49. {
  50. PerformInUiThread(action);
  51. }
  52. else
  53. {
  54. action.Invoke();
  55. }
  56. var remainingTime = minimumMillisecondsBeforeReturn - (Environment.TickCount - startTime);
  57. if (remainingTime > 0)
  58. {
  59. Thread.Sleep(remainingTime);
  60. }
  61. }
  62. public void IgnoreException(Action action)
  63. {
  64. if (action == null)
  65. {
  66. throw new ArgumentNullException("action");
  67. }
  68. try
  69. {
  70. action.Invoke();
  71. }
  72. catch (Exception e)
  73. {
  74. _log.ErrorException("Invocation failed", e);
  75. }
  76. }
  77. /// <summary>
  78. ///
  79. /// </summary>
  80. /// <typeparam name="T"></typeparam>
  81. /// <param name="action"></param>
  82. /// <returns>Default if fails</returns>
  83. public T IgnoreException<T>(Func<T> action)
  84. {
  85. if (action == null)
  86. {
  87. throw new ArgumentNullException("action");
  88. }
  89. try
  90. {
  91. return action.Invoke();
  92. }
  93. catch (Exception e)
  94. {
  95. _log.ErrorException("Invokation failed", e);
  96. return default(T);
  97. }
  98. }
  99. public void Sleep(int milliseconds)
  100. {
  101. Thread.Sleep(milliseconds);
  102. }
  103. public void Sleep(TimeSpan sleepTime)
  104. {
  105. Thread.Sleep(sleepTime);
  106. }
  107. }
  108. }