如果使用OnInitializedAsync方法,则在页面初始化时出现NullReferenceException

问题描述 投票:0回答:1

我有一个简单的应用程序,但是它停止了页面初始化并出现错误

NullReferenceException:对象引用未设置为对象的实例。Site.Shared.MainLayout.BuildRenderTree(RenderTreeBuilder __builder)错误:enter image description here

但是代码中没有复杂的东西。App.razor:

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
  <NotFound>
      <LayoutView Layout="@typeof(MainLayout)">
          <p>Sorry, there's nothing at this address.</p>
      </LayoutView>
  </NotFound>

_ Host.cshtml:enter image description here

MainLayout.razor:enter image description here

StartUpService.cs:enter image description here

page.GetPageGlobalAsync()运行良好,我可以在调试模式下传递此方法。enter image description here

但是出现此错误之后。而且不知道是什么原因,如何获得有关错误的更多信息。

UPD

如果我将代码更改为:

PageGlobal page =  new PageGlobal()

它开始起作用,但是OnInitializedAsync是异步方法,为什么我不能在OnInitializedAsync方法中使用async-await方法?

asp.net-core blazor asp.net-core-3.0
1个回答
0
投票

Task.Run方法定义如下:

排队指定的工作以在ThreadPool上运行并返回任务或该工作的任务句柄

也许这可以解释您的问题。您应该了解Blazor在同一线程JavaScript运行下运行,这是UI线程。没有其他线程可以使用。我想Blazor中的异步编程概念与其他环境中的有所不同。我相信Blazor中的异步编程意味着您可以使用async和await运算符来处理异步性,但是可以在单个线程中进行。我希望我是对的。

您为什么使用Task.Run()?您是否尝试模仿异步性?如果是这样,为什么不使用Task.Delay()...

您正在使用Blazor Server应用程序还是WebAssembly应用程序?如果您使用的是WebAssembly App,我的假设是正确的。 WASM上的Mono当前是单线程的,因此不能使用Task.Run()。如果您使用的是Blazor Server App,则问题可能出在其他地方。

© www.soinside.com 2019 - 2024. All rights reserved.