C# Task.Factory 加 BackgroundWorker 运作方式 [教学、范例]
身为software developer的我,threading真的很难用,我也搞不清楚怎样用。后来经过搜索,发现Task Class比threading更加容易操作使用,但是,只能在.net framework 4.0或以上环境运行。
真的是个好消息,马上升级.net 4.0,真的省去很多时间哦。
我经历好久,以下三个错误是最常见的,只需要根据我以下的code,问题已经解决了。
1. Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
2. Cannot access a disposed object close.
3. The current SynchronizationContext may not be used as a TaskScheduler.
Task Class的运作方式是在后面执行的,所以会产生界面UI同步的问题,如上三个错误。
以下是范例,希望能帮得到你。
有些要注意的地方,如果没经验的话,使用Invoke会产生很多问题,因为控件不会自动dispose,尤其是当formclosing的时候。(当代码没执行完,使用者去按Close Form,会报错误)
this.Invoke(new MethodInvoker(delegate
{
//不建议使用,真的很多问题,FromCurrentSynchronizationContext是自动化的。
}
private void btnTest_Click(object sender, EventArgs e)
{
//不让别人按,锁着
btnTest.Enabled = false;
//这个重要FromCurrentSynchronizationContext是要同步界面的
TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
//执行任务
Task task = Task.Factory.StartNew(() =>
{
//把数字加起来
int iValue = 1 + 1;
//传给下面
return iValue;
}
).ContinueWith(x =>
{
//x.Result是2,加3
int iFinalValue = x.Result + 3;
//再执行BackgroundWorker
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, ee) => WorkerDoWork(iFinalValue, uiScheduler);
worker.RunWorkerAsync();
}, uiScheduler);//记得要放,不然会报错
}private void WorkerDoWork(int iParameter, TaskScheduler uiScheduler)
{
//来个新的任务加字Is The Final Value
Task.Factory.StartNew(() =>
{
return iParameter.ToString() + " Is The Final Value ";
}).ContinueWith(x =>
{
// 当上面执行完后,弹出完成
MessageBox.Show(x.Result + " 'Complete' ");
//解放btnTest按钮
btnTest.Enabled = true;
}, uiScheduler);//记得要放,不然会报错
}
页:
[1]