Advertisement
Guest User

Untitled

a guest
May 4th, 2015
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using System.Windows.Threading;
  8.  
  9. namespace Matteopic
  10. {
  11. class AsyncTask<Result>
  12. {
  13. private Action preExecute;
  14. private Action<Result> postExecute;
  15. private Action<Exception> onException;
  16. private Func<Result> function;
  17.  
  18. public AsyncTask<Result> OnException(Action<Exception> action)
  19. {
  20. this.onException = action;
  21. return this;
  22. }
  23.  
  24. // Run the Action in the GUI Thread
  25. public AsyncTask<Result> OnPreExecute(Action action) {
  26. this.preExecute = action;
  27. return this;
  28. }
  29.  
  30. // Run the Action in the GUI Thread
  31. public AsyncTask<Result> OnPostExecute(Action<Result> action)
  32. {
  33. this.postExecute = action;
  34. return this;
  35. }
  36.  
  37. // Run the Action in a separated Thread
  38. public AsyncTask<Result> DoInBackground(Func<Result> function)
  39. {
  40. this.function = function;
  41. return this;
  42. }
  43.  
  44. public void Start()
  45. {
  46. //Console.WriteLine("Execute");
  47. /**
  48. .NET 4.0
  49. Task.Factory.StartNew((Action)(() =>{}
  50. App.Current.Dispatcher.Invoke((Action)(() =>
  51. {
  52. //Console.WriteLine("Starting PreExecute");
  53. if (preExecute != null) preExecute.Invoke();
  54. }));
  55. ), CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  56. */
  57.  
  58. //.NET 4.5
  59. Task.Run((Action)(() =>
  60. {
  61. App.Current.Dispatcher.Invoke((Action)(() =>
  62. {
  63. //Console.WriteLine("Starting PreExecute");
  64. if (preExecute != null) preExecute.Invoke();
  65. }));
  66. }))
  67.  
  68. .ContinueWith((Func<Task, Result>)((Task t) =>
  69. {
  70. try
  71. {
  72. //Console.WriteLine("Starting Background ");
  73. return function.Invoke();
  74. }catch(Exception ex){
  75. //Console.WriteLine("Starting Exception ");
  76. if (onException != null) onException.Invoke(ex);
  77. return default(Result);
  78. }
  79. }))
  80.  
  81. .ContinueWith((Action<Task<Result>>)((Task<Result> t) =>
  82. {
  83. App.Current.Dispatcher.Invoke((Action)(() =>
  84. {
  85. //Console.WriteLine("Starting PostExecute");
  86. Result res = t.Result;
  87. if (postExecute != null) postExecute.Invoke(res);
  88. }));
  89. }));
  90. //Console.WriteLine("/Execute");
  91. }
  92.  
  93. }
  94.  
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement