在下面的代码中,当我安排新的任务(Task.Factory.StartNew)时,它将冻结UI。任何人都可以帮助我理解这里有什么问题。Task.Factory.Start新冻结UI
public Task ShowHierarchy(IHierarchyFilterStrategy topHierarchyStrategy, IHierarchyFilterStrategy bottomHierarchyStrategy)
{
IEnumerable<IHierarchyNodeViewModel> topList = null;
IEnumerable<IHierarchyNodeViewModel> bottomList = null;
var context = TaskScheduler.FromCurrentSynchronizationContext();
var task = Task.Factory.StartNew(() =>
{
topList = topHierarchyStrategy != null ? topHierarchyStrategy.RetrieveHierarchy().ToList() : null;
bottomList = bottomHierarchyStrategy != null
? bottomHierarchyStrategy.RetrieveHierarchy().ToList()
: null;
});
return task.ContinueWith((antecedent) =>
{
View.SetAvailableNodes(topList, bottomList);
}, context);
}
编辑: 更加具体......我的UI上
topList = topHierarchyStrategy != null ? topHierarchyStrategy.RetrieveHierarchy().ToList() : null;
RetrieveHierarchy越来越块()方法是从缓存中加载一些数据,如果不在缓存中,然后去到DB获取数据。它与UI无关。为了证明,我在这里做的是,我从第一个任务中的缓存/数据库获取两个列表,并使用这两个值更新UI(某些树节点)。但只有当UI尝试从第一行中的RetrieveHierarchy()方法中检索值时,UI才会冻结,否则不会在其他位置冻结。
仅当数据来自数据库时才会出现此问题。一旦它被加载到缓存中,这段代码就没有时间了。
使用以下行调用ShowHierarchy()方法
ShowHierarchy(topHierarchyStrategy,bottomHierarchyStrategy);
我没有在任何地方使用它的返回值。
'RetrieveHierarchy'方法是怎样的?该实现是否会阻止UI线程?或者'SetAvailableNodes'太贵了? –
因为我们没有完整的代码,我们将如何重现这一点? –
尝试在[链接]看到你的答案(http://stackoverflow.com/questions/13934274/problems-with-scheduling-tasks-from-a-ui-continuewith-task) –