c# tpl, continuewith 的问题“调用线程无法访问对象,因为不同的线程拥有它”
我正在运行 Visual Studion 2010 (Net 4.0) 我正在创建一个任务,将一些值加载到 ObservableCollection 中,然后返回到 UI。这是代码:
LoadValues = Task.Factory.StartNew<ObservableCollection<DataGridEntity>>(curDataLoader.LoadValuesTask);
ItemsList = LoadValues.Result;
this.DataContext = ItemsList;
此代码片段工作正常!但使用 .Result 属性,UI 线程会等待,直到 LoadValues 任务返回。 所以我想这样做:
LoadValues = Task.Factory.StartNew<ObservableCollection<DataGridEntity>>(curDataLoader.LoadValuesTask);
LoadValues.ContinueWith((FinishLoadDataToDataGrid1) =>
{
ItemsList = LoadValues.Result;
this.DataContext = ItemsList;
});
差别很小。我使用ContinueWith 来防止UI 线程等待。 但如果我这样做,他告诉我:“调用线程无法访问对象,因为不同的线程拥有它”在“this.DataContext = ItemsList;”
是不是时间问题?有人有什么想法吗?
I'm running Visual Studion 2010 (Net 4.0)
I'm creating a task that loads some values into an ObservableCollection and comes back to the UI after that. This is the code:
LoadValues = Task.Factory.StartNew<ObservableCollection<DataGridEntity>>(curDataLoader.LoadValuesTask);
ItemsList = LoadValues.Result;
this.DataContext = ItemsList;
This code snippet works fine! But with the .Result Property the UI-thread waits until the LoadValues task comes back.
So I want to do it that way:
LoadValues = Task.Factory.StartNew<ObservableCollection<DataGridEntity>>(curDataLoader.LoadValuesTask);
LoadValues.ContinueWith((FinishLoadDataToDataGrid1) =>
{
ItemsList = LoadValues.Result;
this.DataContext = ItemsList;
});
Very little difference. I used ContinueWith to prevent the UI thread from waiting.
But if I do it that way he tells me: "Calling thread cannot access object because different thread owns it" at "this.DataContext = ItemsList;"
Is it a timing problem? Does anyone have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用 TaskScheduler.FromCurrentSynchronizationContext() 在 UI 线程上运行ContinueWith。
You need to use the TaskScheduler.FromCurrentSynchronizationContext() to run the ContinueWith on the UI thread.
因为您正在 UI 线程上工作,并且当您使用 ContinueWith 时,您的 UI 会继续在 UI 线程上执行,并且新任务在 ThreadPool 线程上执行,当新任务完成时,回调函数(在ContinueWith中传递)将在 ThreadPool 线程上执行。
现在回调函数尝试访问 UI 线程拥有的对象,系统会抛出错误。
通过在 TaskScheduler.FromCurrentSynchronizationContext() 上调度回调函数,您可以指示系统在 UI 线程上执行此函数,一切正常。
这只是解释,因为 D.Fihnn 已经回答了你的问题。
Because you are working on UI thread and when you use ContinueWith then your UI keep executing on UI thread and new task is executing on ThreadPool thread and when new task finishes then callback function (which is passed in ContinueWith) will execute on ThreadPool thread.
Now callback function try to access objects owned by UI thread and system throws error.
By scheduling callback function on TaskScheduler.FromCurrentSynchronizationContext(), you direct system to execute this function on UI thread and everything works.
This is just explanation as D.Fihnn has already answer you question.