【发布时间】:2011-11-01 12:01:13
【问题描述】:
我写了这段代码:
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);
}
}
它在 WPF 中有效,但是当我以这种方式编写此代码时;
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);
它不起作用,而 txtReport.Text 具有正确的值,但它不会在操作中间显示,但在操作结束时 txtReport 显示它的值
为什么这段代码不起作用?
【问题讨论】:
-
您的视图模型是否实现了
INotifyPropertyChanged接口? -
您仍然需要告诉 XAML 该属性已更改。
-
请多描述一下我...
-
@ChrisF:我在这里没有看到缺少的 INPC。 OP 直接设置 txttest.Text 。不需要 PropertyChanged 事件。我错了吗?
-
@HCL - 啊 - 我明白你的意思了。我上面的 cmets 是错误的 - 我误解了正在更新的属性。
标签: c# wpf multithreading task