Last active
July 4, 2017 19:48
-
-
Save musoftware/6f8b8dcf8571bc096ce201632dbf1365 to your computer and use it in GitHub Desktop.
My Background Worker in Button Fast
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 BkGround | |
{ | |
public class ResultCls | |
{ | |
public Exception ex { get; set; } | |
public object output { get; set; } | |
public ResultCls() | |
{ | |
} | |
public ResultCls(object output) | |
{ | |
this.output = output; | |
} | |
public ResultCls(Exception ex, object output) : this(output) | |
{ | |
this.ex = ex; | |
} | |
} | |
Func<object> _task { get; set; } | |
Action<ResultCls> _complete { get; set; } | |
BackgroundWorker bgworker = new BackgroundWorker(); | |
private bool _trycatch; | |
public BkGround(bool trycatch) | |
{ | |
// TODO: Complete member initialization | |
this._trycatch = trycatch; | |
} | |
public void Run(Func<object> task, Action<ResultCls> complete) | |
{ | |
if (bgworker.IsBusy) return; | |
this._task = task; | |
this._complete = complete; | |
bgworker.RunWorkerCompleted += bgworker_RunWorkerCompleted; | |
bgworker.DoWork += bgworker_DoWork; | |
bgworker.RunWorkerAsync(); | |
} | |
void bgworker_DoWork(object sender, DoWorkEventArgs e) | |
{ | |
if (this._trycatch) | |
{ | |
try | |
{ | |
var output = this._task(); | |
e.Result = new ResultCls(output); | |
} | |
catch (Exception ex) | |
{ | |
e.Result = new ResultCls(ex); | |
} | |
} | |
else | |
{ | |
var output = this._task(); | |
e.Result = new ResultCls(output); | |
} | |
} | |
void bgworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) | |
{ | |
this._complete(e.Result as ResultCls); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment