C# 调用线程无法访问此对象,因为存在其他问题
这就是我的代码的设置方式。但是,在Method2中更新myUIElement时,我遇到了一个异常 “调用线程无法访问此对象,因为另一个 线程拥有它 等待之后的任何东西都应该在UI线程上调用吗?我在这里做错了什么C# 调用线程无法访问此对象,因为存在其他问题,c#,.net,wpf,async-await,C#,.net,Wpf,Async Await,这就是我的代码的设置方式。但是,在Method2中更新myUIElement时,我遇到了一个异常 “调用线程无法访问此对象,因为另一个 线程拥有它 等待之后的任何东西都应该在UI线程上调用吗?我在这里做错了什么 private async void Method1() { // I want to wait until Method2 is completed before doing anything else in Method1 awa
private async void Method1()
{
// I want to wait until Method2 is completed before doing anything else in Method1
await Task.Factory.StartNew(() => Method2());
}
private async void Method2()
{
// Reading few things from configuration etc
await Task.Factory.StartNew(() => SomeAPILoadDataFromSomewhere());
myUIElement.Text = "something useful has happened";
}
}
当您不希望相关代码在非UI线程中运行时,不应该使用
StartNew
。只需将其完全删除即可
还要注意的是,您应该只使用async void
方法作为顶级事件处理程序。您打算等待的任何异步方法都应该返回任务
您通常也应该使用任务。如果可能,请运行而不是StartNew
//This should return a Task and not void if it is used by another asynchronous method
private async void Method1()
{
await Method2();
DoSomethingElse();
}
private async Task Method2()
{
await Task.Run(() => SomeAPILoadDataFromSomewhere());
myUIElement.Text = "something useful has happened";
}
这会导致UI升级时应用程序挂起在Method2中。@johnsmith那么您不是从UI线程调用Method1
,您应该这样做。或者您是在不应该阻止UI线程的情况下阻止UI线程。