至少当我在我的代码中实现它时,我必须修改 StartNew Task 以获得相同的行为。在我的视图中有一个开始按钮。它的 IsEnabled 属性绑定到视图模型中的布尔值。在没有添加await task.ContinueWith(_ => true);
和return true;
移出 try 块的情况下,PopulateListStartNew 任务不会等待,因此按钮保持启用状态。我更喜欢使用Task.Factory.StartNew
,因为传递 TaskScheduler 会使代码更具可读性(没有 Dispatcher 混乱)。Records 是一个 ObservableCollection。
我认为 Task.Run 基本上是一个快捷方式(每个Task.Run 与 Task.Factory.StartNew。无论如何,我想更好地理解行为上的差异,并且肯定会感谢与使我的示例代码更好有关的任何建议.
public async Task<bool> PopulateListTaskRun(CancellationToken cancellationToken)
{
try
{
await Task.Run(async () =>
{
// Clear the records out first, if any
Application.Current.Dispatcher.InvokeAsync(() => Records.Clear());
for (var i = 0; i < 10; i++)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
// Resharper says do this to avoid "Access to modified closure"
var i1 = i;
Application.Current.Dispatcher.InvokeAsync(() =>
{
Records.Add(new Model
{
Name = NamesList[i1],
Number = i1
});
Status = "cur: " +
i1.ToString(
CultureInfo.InvariantCulture);
});
// Artificial delay so we can see what's going on
await Task.Delay(200);
}
Records[0].Name = "Yes!";
}, cancellationToken);
return true;
}
catch (Exception)
{
return false;
}
}
public async Task<bool> PopulateListStartNew(CancellationToken cancellationToken, TaskScheduler taskScheduler)
{
try
{
var task = await Task.Factory.StartNew(async () =>
{
// Clear the records out first, if any
Records.Clear();
for (var i = 0; i < 10; i++)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
Records.Add(new Model
{
Name = NamesList[i],
Number = i
});
Status = "cur: " +
i.ToString(
CultureInfo.InvariantCulture);
// Artificial delay so we can see what's going on
await Task.Delay(200);
}
Records[0].Name = "Yes!";
}, cancellationToken, TaskCreationOptions.None, taskScheduler);
// Had to add this
await task.ContinueWith(_ => true);
}
catch (Exception)
{
return false;
}
// Had to move this out of try block
return true;
}