是否有可能鏈接具有不同返回類型或根本沒有返回類型的任務?例如,在僞代碼:具有不同返回類型的鏈接任務
Task<double>.ContinueWith(Task<string>).ContinueWith(Task<String>).ContinueWith(Task)
或者也在這裏是真實的代碼示例:
private double SumRootN(int root)
{
double result = 0;
for (int i = 1; i < 10000000; i++)
{
result += Math.Exp(Math.Log(i)/root);
}
return result;
}
private void taskSequentialContinuationButton_Click(object sender, RoutedEventArgs e)
{
Task<double> task = null;
this.statusText.Text = "";
this.watch = Stopwatch.StartNew();
for (int i = 2; i < 20; i++)
{
int j = i;
if (task == null)
{
task = Task<double>.Factory.StartNew(() => { return SumRootN(j); });
}
else
{
task = task.ContinueWith((t) => { return SumRootN(j); });
}
task = task.ContinueWith((t) =>
{ // I don't want to return anything from this task but I have to, to get it to compile
this.statusText.Text += String.Format("root {0} : {1}\n", j, t.Result);
return t.Result;
}, TaskScheduler.FromCurrentSynchronizationContext());
}
task.ContinueWith((t) =>
{ // I also don't want to return anything here but I don't seem to have to here even though intellisense expects a Task<double>??
this.statusText.Text += String.Format("{0}ms elapsed\n", watch.ElapsedMilliseconds);
}, TaskScheduler.FromCurrentSynchronizationContext());
}
請參閱鏈接的怪事內嵌批註。
爲什麼你有這麼多'任務'的順序?難道你不能在一個Task中運行循環,這會創建'SynchronizationContext'' Task's? – svick
這確實是一個更好的解決方案,但是如何在不同的線程上獲得單個任務中的UI線程上下文?我知道這可以用Dispatcher完成,但是這會使代碼依賴於UI框架。是否有可能傳入對UI線程的引用?你能做一個代碼示例嗎? – flolim
我認爲這裏的代碼示例可能會造成更多的傷害。你能從運行時行爲的角度解釋你正在尋找什麼?由於您的ContinueWith調用不使用't'或't.Result' –