gpt4 book ai didi

c# - 如何在 TaskScheduler.FromCurrentSychronizationContext 的延续中使用 Task.Result?

转载 作者:行者123 更新时间:2023-12-03 10:59:51 25 4
gpt4 key购买 nike

在 WPF 应用程序中,我有一个按钮绑定(bind)到我的 View 模型中的命令。该命令启动一个任务以从数据库中获取信息,然后更新一些属性。

//list in vm to be bound to..
List<DataModel.Item> BoundList;
//new command () =>
{
var t = Task.Factory.StartNew<IEnumerable<DataModel.Item>>( () =>
return datasvc.GetItems();
);
t.ContinueWith( t2 => {
BoundList = t.Result;
}, TaskScheduler.FromCurrentSychronizationContext);
}

项目在 t.Result 上报告构建错误当我使用 FromCurrentSynchronizationContext标志,但是当它不存在时,没有构建错误。问题是我得到一个无响应的用户界面。

我做错了什么?

最佳答案

这不是一个标志,它是一个静态方法。此外, t2 是任务的结果,因此您不需要将原始任务存储为单独的变量:

Task.Factory.StartNew(datasvc.GetItems)
.ContinueWith(
t =>
{
BoundList = t.Result;
}, TaskScheduler.FromCurrentSychronizationContext());

如果您是 Task对象正在 UI 线程中运行(因此卡住它),这可能是因为您已经在线程池中运行了许多线程。默认情况下, Task将在 ThreadPool 上运行线程,除非它们都被使用。

但是,您可以告知 .NET 这是一个长时间运行的操作,并且它通常会生成额外的线程来阻止您的 UI 卡住。

来自 MSDN :

TaskCreationOptions.LongRunning
Specifies that a task will be a long-running, coarse-grained operation involving fewer, larger components than fine-grained systems. It provides a hint to the TaskScheduler that oversubscription may be warranted. Oversubscription lets you create more threads than the available number of hardware threads.



因此,您可以将任务创建更改为:
Task.Factory.StartNew(datasvc.GetItems, TaskCreationOptions.LongRunning)

关于c# - 如何在 TaskScheduler.FromCurrentSychronizationContext 的延续中使用 Task.Result?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17532117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com