【问题标题】:Famous the calling thread cannot access this object because a different issue著名的调用线程无法访问此对象,因为另一个问题
【发布时间】:2015-03-05 22:57:30
【问题描述】:

这就是我的代码的设置方式。但是,在 Method2 中更新 myUIElement 时出现异常。

"调用线程无法访问该对象,因为不同的 线程拥有它。

是否应该在 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"; 


            }
        }

【问题讨论】:

    标签: c# .net wpf async-await


    【解决方案1】:

    当您实际上不希望相关代码在非 UI 线程中运行时,您不应该使用 StartNew。完全删除它。

    还请注意,您应该只将 async void 方法作为顶级事件处理程序。您打算 await 的任何异步方法都应返回 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";             
    }
    

    【讨论】:

    • 当 UI 更新时,这会导致应用程序在 Method2 中挂起。
    • @johnsmith 那么你没有从 UI 线程调用 Method1,你应该这样做。或者,当您不应该阻塞 UI 线程时,您正在阻塞 UI 线程。
    猜你喜欢
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2022-01-13
    相关资源
    最近更新 更多