为什么以这种方式使用 System.Threading.Task 类时我的 UI 被阻止?
在我的 ViewModel 中,我有以下代码:
Logs = new ObservableCollection<Log>();
Logs = Task.Factory.StartNew(() => mainModel.GetLogs()).Result;
Log 是一个非常简单的类,具有几个公共属性。
根据我对 Task 类的理解,以这种方式调用的 mainModel 函数 GetLogs() 应该在单独的线程上运行,当它从数据库中获取记录时,我的 UI 应该做出响应,但这不是正在发生的情况,而是在记录被读取时从数据存储中获取我的 UI 被阻止。
我希望有人能解释为什么......TIA。
编辑:我对 Task 类的理解不完整,使用 Task 类的ContinueWith 方法将确保异步执行,如下面成员回复中所述...
In my ViewModel I have this code:
Logs = new ObservableCollection<Log>();
Logs = Task.Factory.StartNew(() => mainModel.GetLogs()).Result;
wtih Log being a very simple class with a couple of public properties.
According to my understanding of Task class the mainModel function GetLogs() invoked this way should run on a separate thread and while it is fetching records from the database my UI should be responsive, however that is not what is happening, instead while records are being fetched from the data store my UI is blocked.
I was hoping someone could explain why... TIA.
EDIT: My understading of the Task class was incomplete, using ContinueWith method of the Task class will ensure the async execution as explained below in member replies...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为您在开始异步操作后立即调用
Result
。Result
属性的 getter 会阻塞当前线程的执行,直到任务完成。更新:
为了异步获取结果,您需要调用
ContinueWith
并指定任务完成时将调用的函数:This is because you call
Result
right after you started the asynchronous operation. The getter of theResult
property blocks the execution of current thread until the task is completed.Update:
In order to get the result asynchronously, you need to call
ContinueWith
and specify a function that will be called when the task is completed:我认为您不应该像这样使用 Result 属性,来自 MSDN:
如果您在任务运行时访问当前线程,它会使当前线程等待。
You should not use the Result property like this i think, from MSDN:
It makes the current thread wait if you access it while the task is running.
假设 mainModel.GetLogs 是线程安全的,您可能需要这样的东西,它在后台线程上调用 GetLogs,然后仅在完成获取日志时将 Logs 设置为结果。 TaskScheduler.FromCurrentSynchronizationContext() 确保该部分的执行在 UI 线程上运行,如果您的 UI 绑定到该集合,则需要这样做。
Assuming mainModel.GetLogs is threadsafe you probably want something like this, which calls the GetLogs on a background thread, and then only sets Logs to the result when it finished gettings the logs. The TaskScheduler.FromCurrentSynchronizationContext() ensures that execution of that part is run on the UI thread, which will be required if your UI is bound to that collection.