Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows.Threading;
- namespace Matteopic
- {
- class AsyncTask<Result>
- {
- private Action preExecute;
- private Action<Result> postExecute;
- private Action<Exception> onException;
- private Func<Result> function;
- public AsyncTask<Result> OnException(Action<Exception> action)
- {
- this.onException = action;
- return this;
- }
- // Run the Action in the GUI Thread
- public AsyncTask<Result> OnPreExecute(Action action) {
- this.preExecute = action;
- return this;
- }
- // Run the Action in the GUI Thread
- public AsyncTask<Result> OnPostExecute(Action<Result> action)
- {
- this.postExecute = action;
- return this;
- }
- // Run the Action in a separated Thread
- public AsyncTask<Result> DoInBackground(Func<Result> function)
- {
- this.function = function;
- return this;
- }
- public void Start()
- {
- //Console.WriteLine("Execute");
- /**
- .NET 4.0
- Task.Factory.StartNew((Action)(() =>{}
- App.Current.Dispatcher.Invoke((Action)(() =>
- {
- //Console.WriteLine("Starting PreExecute");
- if (preExecute != null) preExecute.Invoke();
- }));
- ), CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
- */
- //.NET 4.5
- Task.Run((Action)(() =>
- {
- App.Current.Dispatcher.Invoke((Action)(() =>
- {
- //Console.WriteLine("Starting PreExecute");
- if (preExecute != null) preExecute.Invoke();
- }));
- }))
- .ContinueWith((Func<Task, Result>)((Task t) =>
- {
- try
- {
- //Console.WriteLine("Starting Background ");
- return function.Invoke();
- }catch(Exception ex){
- //Console.WriteLine("Starting Exception ");
- if (onException != null) onException.Invoke(ex);
- return default(Result);
- }
- }))
- .ContinueWith((Action<Task<Result>>)((Task<Result> t) =>
- {
- App.Current.Dispatcher.Invoke((Action)(() =>
- {
- //Console.WriteLine("Starting PostExecute");
- Result res = t.Result;
- if (postExecute != null) postExecute.Invoke(res);
- }));
- }));
- //Console.WriteLine("/Execute");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement