Skip to content

Instantly share code, notes, and snippets.

@FusRoDah061
Created March 28, 2019 17:17
Show Gist options
  • Save FusRoDah061/3feeae389bd598fc73f14c886163256c to your computer and use it in GitHub Desktop.
Save FusRoDah061/3feeae389bd598fc73f14c886163256c to your computer and use it in GitHub Desktop.
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