Async.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. namespace EZXR.Glass.Core.Threading
  4. {
  5. public class Async
  6. {
  7. private static Dispatcher Dispatcher
  8. {
  9. get { return Dispatcher.Instance; }
  10. }
  11. private static readonly Dictionary<string, object> Locks = new Dictionary<string, object>();
  12. public static AsyncTask Run(Action action)
  13. {
  14. AsyncTask asyncTask = new AsyncTask(action);
  15. Dispatcher.RegisterTask(asyncTask);
  16. return asyncTask;
  17. }
  18. public static AsyncTask<T> Run<T>(Func<T> func)
  19. {
  20. AsyncTask<T> asyncTask = new AsyncTask<T>(func);
  21. Dispatcher.RegisterTask(asyncTask);
  22. return asyncTask;
  23. }
  24. public static AsyncTask RunInBackground(string taskName, int runFrequencyMs, Action action)
  25. {
  26. if (Dispatcher.HasBackgroundTask(taskName) == false)
  27. {
  28. AsyncTask asyncTask = new AsyncTask(action, runFrequencyMs);
  29. Dispatcher.RegisterBackgroundTask(taskName, asyncTask);
  30. return asyncTask;
  31. }
  32. return Dispatcher.GetBackgroundTask(taskName);
  33. }
  34. public static AsyncTask<T> RunInBackground<T>(string taskName, int runFrequencyMs, Func<T> func)
  35. {
  36. if (Dispatcher.HasBackgroundTask(taskName) == false)
  37. {
  38. AsyncTask<T> asyncTask = new AsyncTask<T>(func, runFrequencyMs);
  39. Dispatcher.RegisterBackgroundTask(taskName, asyncTask);
  40. return asyncTask;
  41. }
  42. var genericAsyncTask = Dispatcher.GetBackgroundTask(taskName) as AsyncTask<T>;
  43. if (genericAsyncTask == null)
  44. {
  45. throw new InvalidOperationException("Cannot find requested generic AsyncTask with name " + taskName);
  46. }
  47. return genericAsyncTask;
  48. }
  49. public static object GetLock(string key)
  50. {
  51. object lockObj;
  52. Locks.TryGetValue(key, out lockObj);
  53. if (lockObj == null)
  54. {
  55. lockObj = new object();
  56. Locks.Add(key, lockObj);
  57. }
  58. return lockObj;
  59. }
  60. }
  61. }