I wrote this code:
public double SumRootN(int root)
{
double result = 0;
for (int i = 1; i < 10000000; i++)
{
tokenSource.Token.ThrowIfCancellationRequested();
result += Math.Exp(Math.Log(i) / root);
}
return result;
}
private void btnclick_Click(object sender, RoutedEventArgs e)
{
tokenSource = new CancellationTokenSource();
txttest.Text = "";
var watch = Stopwatch.StartNew();
List<Task> tasks = new List<Task>();
var ui = TaskScheduler.FromCurrentSynchronizationContext();
for (int i = 2; i < 20; i++)
{
int j = i;
var compute = Task.Factory.StartNew(() =>
{
return SumRootN(j);
}, tokenSource.Token);
tasks.Add(compute);
var displayResults = compute.ContinueWith(
resultTask =>
txttest.Text
+= "root " + j.ToString() + " " +
compute.Result.ToString() +
Environment.NewLine,
CancellationToken.None,
TaskContinuationOptions.OnlyOnRanToCompletion,
ui);
}
}
It works in WPF but when I wrote this code this way;
tokenSource = new CancellationTokenSource();
var watch = Stopwatch.StartNew();
List<Task> tasks = new List<Task>();
var ui = TaskScheduler.FromCurrentSynchronizationContext();
Report
+= ((Microsoft.Office.Interop.Excel.Range)_sheet.Cells[row, "B"]).Value2;
var compute = Task.Factory.StartNew(() =>
{
return Report;
}, tokenSource.Token);
tasks.Add(compute);
var displayResults
= compute.ContinueWith(resultTask =>
txtReport.Text
+= compute.Result.ToString() +
Environment.NewLine,
CancellationToken.None,
TaskContinuationOptions.OnlyOnRanToCompletion,
ui);
It does not work, whereas txtReport.Text has correct values, but it does not show in the middle of operation but when operation ends txtReport show it’s values
Why does this code not work?
ContinueWithcreates a continuation that executes asynchronously when the target Task completes. I.e it will only update the result once yourSumRootNoperation complete.