Created
March 28, 2019 17:17
-
-
Save FusRoDah061/3feeae389bd598fc73f14c886163256c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AsyncTask<T> | |
{ | |
private BackgroundWorker _worker; | |
public bool Success { get; private set; } | |
public Exception Error { get; private set; } | |
public T Data { get; set; } | |
public bool WaitingCancelation { get | |
{ | |
if(_worker != null) | |
return _worker.CancellationPending; | |
return false; | |
} | |
} | |
public AsyncTask() | |
{ | |
_worker = new BackgroundWorker(); | |
_worker.WorkerSupportsCancellation = true; | |
_worker.WorkerReportsProgress = true; | |
} | |
public void SetOnFinish(RunWorkerCompletedEventHandler callback) | |
{ | |
_worker.RunWorkerCompleted += callback; | |
} | |
public void SetOnProgress(ProgressChangedEventHandler callback) | |
{ | |
_worker.ProgressChanged += callback; | |
} | |
public void SetWork(DoWorkEventHandler action) | |
{ | |
Success = true; | |
_worker.DoWork += (sender, e) => | |
{ | |
try | |
{ | |
if (!_worker.CancellationPending) | |
action(sender, e); | |
} | |
catch (Exception ex) | |
{ | |
Success = false; | |
Error = ex; | |
} | |
}; | |
} | |
public void Run() | |
{ | |
_worker.RunWorkerAsync(); | |
} | |
public void Cancel() | |
{ | |
_worker.CancelAsync(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment