著名的调用线程无法访问此对象,因为另一个问题

Famous the calling thread cannot access this object because a different issue

我的代码是这样设置的。但是,在 Method2.

中更新我的 UIElement 时出现异常

"the calling thread cannot access this object because a different thread owns it.

是否应该始终在 UI 线程上调用 await 之后的任何内容?我在这里做错了什么?

 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 方法作为顶级事件处理程序。您打算 await 的任何异步方法都应该 return a Task.

您通常还应该尽可能使用 Task.Run 而不是 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";             
}