OnInitializedAsync() 被调用了两次。

huangapple go评论83阅读模式
英文:

OnInitializedAsync() is being called twice

问题

以下是您要翻译的内容:

For some reason when bringing up the page CampaignPage.razor, `OnInitializedAsync()` is being called twice.

In addition, the property `ReturnUrl` is null each time (should be the first time) and is null again when `HandleValidSubmitAsync()` is called.

The first time it hits it, this is the call stack:

    LouisHowe.web.dll!LouisHowe.web.Pages.Manager.CampaignPage.OnInitializedAsync() Line 143    C#
    [External Code]    
    LouisHowe.web.dll!LouisHowe.web.Pages.Pages__Host.ExecuteAsync.AnonymousMethod__23_1() Line 40    C#
    [External Code]    

And the second time, this is it:

    LouisHowe.web.dll!LouisHowe.web.Pages.Manager.CampaignPage.OnInitializedAsync() Line 143    C#
    [External Code]    

In addition it's 5+ seconds between the two hits and there's very little the system is doing to initialize the page. It hits the database but that's Sql Server Express sitting on my computer doing nothing else.

This only happens for case of mode == read or update. And in that case, in `OnInitializedAsync()` it is calling the following code. So it's something in this code that is causing the issue.

Note that it calls the same dbContext to get `Countries.All()` for the case of mode == create and that does not have the problem. So it's something in the call to `Campaigns.FindByNames()` that's doing it - but how?

await using (var dbContext = await NoTrackingDbFactory.CreateDbContextAsync())
{
    // 1. if no uniqueId then create mode (because what would we Read/Update)?
    if (string.IsNullOrEmpty(UniqueId))
        ModeState = Mode.Create;
    else
    {
        // 2. if have a uniqueId then it can't be create.
        if (ModeState == Mode.Create)
            ModeState = Mode.Read;

        // 3. Read it in from the database.
        _campaign = await dbContext.Campaigns.FindByNames(string.Empty, 
                UniqueId, CampaignIncludes.All).FirstOrDefaultAsync();
        if (_campaign == null)
        {
            _badUniqueId = true;
            ModeState = Mode.Read;
            return;
        }

        Model.Campaign = _campaign;
    }

    var list = new List<IOrganization>();
    list.AddRange(await dbContext.Countries.All().ToListAsync());
    list.Add(Country.Dashes);
    list.AddRange(await dbContext.States.All().ToListAsync());
    AllRegions = list;
}
And here's `FindByNames`

public static IQueryable<Campaign> FindByNames(this IQueryable<Campaign> source, string searchName, 
    string searchUniqueId, params Expression<Func<Campaign, object?>>[] includes)
{
    var query = source;
    if (searchName.Length != 0)
        query = query.Where(campaign => campaign.Name.Contains(searchName));
    if (searchUniqueId.Length != 0)
        query = query.Where(campaign => campaign.UniqueId.Contains(searchUniqueId));
    foreach (var include in includes)
        query = query.Include(include);
    return query.OrderBy(i => i.Name);
}

So, what would cause the long delay and the multiple calls?
So I did as @MrCakaShaunCurtis suggested and put a debug entering and leaving `OnInitializedAsync()` and here's what I get.
Only once case (mode == create):
enter OnInitializedAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
... 2 expected DB calls
leave OnInitializedAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
enter OnAfterRenderAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
leave OnAfterRenderAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
enter OnAfterRenderAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
leave OnAfterRenderAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
And for the calls twice case:
enter OnInitializedAsync() CampaignPage Instance 427cd0b9-bf07-41d7-924f-0355da16b441
... 4 (FindByNames query becomes 2 calls) expected DB calls
leave OnInitializedAsync() CampaignPage Instance 427cd0b9-bf07-41d7-924f-0355da16b441
Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (2ms) [Parameters=[@__userid_0='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
SELECT TOP(1) [a].[Id], [a].[AccessFailedCount], [a].[ConcurrencyStamp], [a].[Email], [a].[EmailConfirmed], [a].[LockoutEnabled], [a].[LockoutEnd], [a].[NormalizedEmail], [a].[NormalizedUserName], [a].[PasswordHash], [a].[PhoneNumber], [a].[PhoneNumberConfirmed], [a].[SecurityStamp], [a].[TwoFactorEnabled], [a].[UserName]
FROM [AspNetUsers] AS [a]
WHERE [a].[Id] = @__userid_0
enter OnInitializedAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
... 4 calls again
leave OnInitializedAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
'LouisHowe.web.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\7.0.5\System.Web.HttpUtility.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
enter OnAfterRenderAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
leave OnAfterRenderAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
'LouisHowe.web.exe' (CoreCLR: clrhost): Loaded 'C:\git\LouisHowe\LouisHowe.web\bin\Debug\net7.0\Newtonsoft.Json.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
enter OnAfterRenderAsync() CampaignPage Instance 2
<details>
<summary>英文:</summary>
For some reason when bringing up the page CampaignPage.razor, `OnInitializedAsync()` is being called twice.
In addition, the property `ReturnUrl` is null each time (should be the first time) and is null again when `HandleValidSubmitAsync()` is called.
The first time it hits it, this is the call stack:
LouisHowe.web.dll!LouisHowe.web.Pages.Manager.CampaignPage.OnInitializedAsync() Line 143	C#
[External Code]	
LouisHowe.web.dll!LouisHowe.web.Pages.Pages__Host.ExecuteAsync.AnonymousMethod__23_1() Line 40	C#
[External Code]	
And the second time, this is it:
LouisHowe.web.dll!LouisHowe.web.Pages.Manager.CampaignPage.OnInitializedAsync() Line 143	C#
[External Code]	
In addition it&#39;s 5+ seconds between the two hits and there&#39;s very little the system is doing to initialize the page. It hits the database but that&#39;s Sql Server Express sitting on my computer doing nothing else.
This only happens for case of mode == read or update. And in that case, in `OnInitializedAsync()` it is calling the following code. So it&#39;s something in this code that is causing the issue.
Note that it calls the same dbContext to get `Countries.All()` for the case of mode == create and that does not have the problem. So it&#39;s something in the call to `Campaigns.FindByNames()` that&#39;s doing it - but how?
await using (var dbContext = await NoTrackingDbFactory.CreateDbContextAsync())
{
// 1. if no uniqueId then create mode (because what would we Read/Update)?
if (string.IsNullOrEmpty(UniqueId))
ModeState = Mode.Create;
else
{
// 2. if have a uniqueId then it can&#39;t be create.
if (ModeState == Mode.Create)
ModeState = Mode.Read;
// 3. Read it in from the database.
_campaign = await dbContext.Campaigns.FindByNames(string.Empty, 
UniqueId, CampaignIncludes.All).FirstOrDefaultAsync();
if (_campaign == null)
{
_badUniqueId = true;
ModeState = Mode.Read;
return;
}
Model.Campaign = _campaign;
}
var list = new List&lt;IOrganization&gt;();
list.AddRange(await dbContext.Countries.All().ToListAsync());
list.Add(Country.Dashes);
list.AddRange(await dbContext.States.All().ToListAsync());
AllRegions = list;
}
And here&#39;s `FindByNames`
public static IQueryable&lt;Campaign&gt; FindByNames(this IQueryable&lt;Campaign&gt; source, string searchName, 
string searchUniqueId, params Expression&lt;Func&lt;Campaign, object?&gt;&gt;[] includes)
{
var query = source;
if (searchName.Length != 0)
query = query.Where(campaign =&gt; campaign.Name.Contains(searchName));
if (searchUniqueId.Length != 0)
query = query.Where(campaign =&gt; campaign.UniqueId.Contains(searchUniqueId));
foreach (var include in includes)
query = query.Include(include);
return query.OrderBy(i =&gt; i.Name);
}
So, what would cause the long delay and the multiple calls?
----------
So I did as @MrCakaShaunCurtis suggested and put a debug entering and leaving `OnInitializedAsync()` and here&#39;s what I get.
Only once case (mode == create):
enter OnInitializedAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
... 2 expected DB calls
leave OnInitializedAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
enter OnAfterRenderAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
leave OnAfterRenderAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
enter OnAfterRenderAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
leave OnAfterRenderAsync() CampaignPage Instance a69f0a2d-e36a-4297-b8a1-d8d9cd12bbd1
And for the calls twice case:
enter OnInitializedAsync() CampaignPage Instance 427cd0b9-bf07-41d7-924f-0355da16b441
... 4 (FindByNames query becomes 2 calls) expected DB calls
leave OnInitializedAsync() CampaignPage Instance 427cd0b9-bf07-41d7-924f-0355da16b441
Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (2ms) [Parameters=[@__userid_0=&#39;?&#39; (Size = 450)], CommandType=&#39;Text&#39;, CommandTimeout=&#39;30&#39;]
SELECT TOP(1) [a].[Id], [a].[AccessFailedCount], [a].[ConcurrencyStamp], [a].[Email], [a].[EmailConfirmed], [a].[LockoutEnabled], [a].[LockoutEnd], [a].[NormalizedEmail], [a].[NormalizedUserName], [a].[PasswordHash], [a].[PhoneNumber], [a].[PhoneNumberConfirmed], [a].[SecurityStamp], [a].[TwoFactorEnabled], [a].[UserName]
FROM [AspNetUsers] AS [a]
WHERE [a].[Id] = @__userid_0
enter OnInitializedAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
... 4 calls again
leave OnInitializedAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
&#39;LouisHowe.web.exe&#39; (CoreCLR: clrhost): Loaded &#39;C:\Program Files\dotnet\shared\Microsoft.NETCore.App\7.0.5\System.Web.HttpUtility.dll&#39;. Skipped loading symbols. Module is optimized and the debugger option &#39;Just My Code&#39; is enabled.
enter OnAfterRenderAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
leave OnAfterRenderAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
&#39;LouisHowe.web.exe&#39; (CoreCLR: clrhost): Loaded &#39;C:\git\LouisHowe\LouisHowe.web\bin\Debug\net7.0\Newtonsoft.Json.dll&#39;. Skipped loading symbols. Module is optimized and the debugger option &#39;Just My Code&#39; is enabled.
enter OnAfterRenderAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
leave OnAfterRenderAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
enter OnAfterRenderAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
leave OnAfterRenderAsync() CampaignPage Instance 2b5a7537-85cc-4bca-9b29-403f8cdba668
So it&#39;s calling the Identity DB to get the `AspNetUsers` user record. It generally does that before each call to `OnInitializedAsync()`, I assume to initialize the value in the `Task&lt;AuthenticationState&gt;` cascading parameter.
So it&#39;s re-initializing, before ever getting to `OnAfterRenderAsync()`.
I made the change @MarvinKlein suggested (2 places) - **that fixed it.** I now have:
@page &quot;/&quot;
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Mvc.TagHelpers
@using LouisHowe.web
@namespace LouisHowe.web.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;!-- Copyright (c) 2023 by David Thielen - ALL RIGHTS RESERVED --&gt;
&lt;meta charset=&quot;utf-8&quot;/&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;/&gt;
&lt;base href=&quot;~/&quot;/&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;css/bootstrap/bootstrap.min.css&quot;/&gt;
&lt;link href=&quot;_content/DevExpress.Blazor.Themes/blazing-berry.bs5.min.css&quot; rel=&quot;stylesheet&quot;
asp-append-version=&quot;true&quot;/&gt;
&lt;link href=&quot;css/site.css&quot; rel=&quot;stylesheet&quot; asp-append-version=&quot;true&quot;/&gt;
&lt;link href=&quot;css/menu.css&quot; rel=&quot;stylesheet&quot; asp-append-version=&quot;true&quot;/&gt;
&lt;link href=&quot;css/header.css&quot; rel=&quot;stylesheet&quot; asp-append-version=&quot;true&quot;/&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;css/dx-demo.css&quot; asp-append-version=&quot;true&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;css/dx-demo-pages.css&quot; asp-append-version=&quot;true&quot;&gt;
&lt;link href=&quot;LouisHowe.web.styles.css&quot; rel=&quot;stylesheet&quot;/&gt;
&lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;favicon.png&quot;/&gt;
&lt;script src=&quot;~/js/Interop.js&quot;&gt;&lt;/script&gt;
&lt;component type=&quot;typeof(HeadOutlet)&quot; render-mode=&quot;Server&quot;/&gt;
&lt;/head&gt;
&lt;body&gt;
@{
var initialTokenState = new Services.InitialApplicationState
{
XsrfToken = Xsrf.GetAndStoreTokens(HttpContext).RequestToken,
Cookie = HttpContext.Request.Cookies[&quot;.AspNetCore.Cookies&quot;]
};
}
&lt;component type=&quot;typeof(App)&quot; render-mode=&quot;Server&quot; param-InitialState=&quot;initialTokenState&quot; /&gt;
&lt;div id=&quot;blazor-error-ui&quot;&gt;
&lt;environment include=&quot;Staging,Production&quot;&gt;
An error has occurred. This application may no longer respond until reloaded.
&lt;/environment&gt;
&lt;environment include=&quot;Development&quot;&gt;
An unhandled exception has occurred. See browser dev tools for details.
&lt;/environment&gt;
&lt;a href=&quot;&quot; class=&quot;reload&quot;&gt;Reload&lt;/a&gt;
&lt;a class=&quot;dismiss&quot;&gt;&#128473;&lt;/a&gt;
&lt;/div&gt;
&lt;script src=&quot;_framework/blazor.server.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
[And this is explained here.][1] Which leads to another question [that I&#39;ll post separately.][2]
[1]: https://stackoverflow.com/questions/58229732/whats-the-difference-between-rendermode-server-and-rendermode-serverprerendered
[2]: https://stackoverflow.com/questions/76452794/what-is-the-best-way-in-blazor-to-initialize-a-page-that-hits-the-db-to-initiali
</details>
# 答案1
**得分**: 0
以下是翻译好的内容:
不可能的。`OnInitialized{Async}` 不会被调用两次,你正在创建两个组件实例(或手动调用它)。 你需要找出为什么会创建两个实例。 你的代码对你来说可能很明显,但对我来说没有太多的上下文,所以我觉得它相当难理解。
为了证明这一点,为组件实例创建一个唯一的ID,并将信息记录到输出。 以下是使用 `Index` 来实现的方式:
```csharp
@page &quot;/&quot;
@using System.Diagnostics;
&lt;PageTitle&gt;Index&lt;/PageTitle&gt;
&lt;h1&gt;Hello, world!&lt;/h1&gt;
欢迎来到你的新应用程序。
&lt;SurveyPrompt Title=&quot;Blazor对你来说如何工作?&quot; /&gt;
@code {
public Guid Uid { get; init; } = Guid.NewGuid();
protected override Task OnInitializedAsync()
{
Debug.WriteLine($&quot;初始化组件 {this.GetType().Name} 实例 {this.Uid.ToString()}&quot;);
return base.OnInitializedAsync();
}
}

在调试时,进行大量的调试输出以观察发生的事情和事件的顺序。当你运行异步代码时,断点通常无法提供足够的信息。人类太慢了!

英文:

Not possible. OnInitialized{Async} isn't called twice, your creating two instances of the component (or manually calling it). You need to figure out why you're creating two instances. Your code may be obvious to you, but to me it's pretty opaque without a lot of context.

To prove it, create a Unique ID for the component instance and log information to Output. Here's how to do it with Index

@page &quot;/&quot;
@using System.Diagnostics;

&lt;PageTitle&gt;Index&lt;/PageTitle&gt;

&lt;h1&gt;Hello, world!&lt;/h1&gt;

Welcome to your new app.

&lt;SurveyPrompt Title=&quot;How is Blazor working for you?&quot; /&gt;

@code {
    public Guid Uid { get; init; } = Guid.NewGuid();

    protected override Task OnInitializedAsync()
    {
        Debug.WriteLine($&quot;Initialized Component {this.GetType().Name} Instance {this.Uid.ToString()}&quot;);
        return base.OnInitializedAsync();
    }
}

When debugging do lots of debug writes to watch what happens and the sequence of events. Break points often tell you nothing when you have async code running. Humans are just toooo slow!

答案2

得分: 0

这个答案是由@MarvinKlein在评论中提供的。

_Host.cshtml 中设置 render-mode=&quot;Server&quot;(两个位置),然后 OnInitializedAsync() 只会被调用一次。

英文:

This answer was provided by @MarvinKlein above in a comment.

In _Host.cshtml set render-mode=&quot;Server&quot; (two locations) and then OnInitializedAsync() will only be called once.

huangapple
  • 本文由 发表于 2023年6月12日 02:37:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451978.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定