我试图实现自己的基本BackgroundWorker,因为Compact Framework没有提供,所以建议在UI线程上调用WorkCompletedHandler吗?
CustomBackgroundWorker类:
public delegate void DoWorkHandler(object sender, DoWorkArgs e);
public delegate void WorkCompletedHandler(object sender, WorkCompletedArgs e);
class CustomBackgroundWorker
{
private System.Windows.Forms.Control _owning_control;
private System.Threading.Thread _t;
private Exception _e = null;
public event DoWorkHandler DoWork;
public event WorkCompletedHandler WorkCompleted;
public CustomBackgroundWorker(System.Windows.Forms.Control Owning_Control)
{
if (Owning_Control == null) throw new ArgumentNullException("Owning_Control");
_owning_control = Owning_Control;
}
public void RunWorkerAsync()
{
this.RunWorkerAsync(null);
}
public void RunWorkerAsync(object Parameter)
{
if (DoWork == null) throw new Exception("DoWork Event isn't subscribed.");
DoWorkArgs dowork_args = new DoWorkArgs(Parameter);
_t = new Thread(() =>
{
try
{
DoWork(this, dowork_args);
}
catch (Exception ex)
{
_e = ex;
}
if (WorkCompleted != null)
{
_owning_control.BeginInvoke(new Action(() =>
{
WorkCompleted(this, new WorkCompletedArgs(_e, dowork_args.Result));
}));
}
});
_t.Name = "BackgroundWorker Thread";
_t.Start();
}
}
public class DoWorkArgs
{
public object Result { get; set; }
public object Parameter { get; private set; }
public DoWorkArgs(object Parameter)
{
this.Parameter = Parameter;
}
}
public class WorkCompletedArgs
{
private object _result;
public WorkCompletedArgs(Exception Error, object Result)
{
this.Error = Error;
_result = Result;
}
public object Result
{
get
{
if (this.Error != null) throw new Exception("Can't access Result, during execution an Exception was thrown.");
return _result;
}
}
public object Error { get; private set; }
}
示例用法:
Thread.CurrentThread.Name = "UI Thread!";
CustomBackgroundWorker bgw = new CustomBackgroundWorker(this);
bgw.DoWork += new DoWorkHandler((o, args) =>
{
Debug.WriteLine("Thread: " + Thread.CurrentThread.Name);
for (int i = 0; i < 10; i++)
{
Debug.WriteLine("Tick: " + i.ToString());
Thread.Sleep(1000);
args.Result = i;
}
});
bgw.WorkCompleted += new WorkCompletedHandler((o, args) =>
{
Debug.WriteLine("Thread: " + Thread.CurrentThread.Name);
if (args.Error == null)
{
Debug.WriteLine("Result: " + args.Result.ToString());
}
});
bgw.RunWorkerAsync();