.net 获取Timer类以更改布尔值的状态,并从应用程序中删除GIF,但网站冻结

2cmtqfgy  于 2023-02-26  发布在  .NET
关注(0)|答案(1)|浏览(84)

我有一个gif文件,每当有人创建一本新书时,我都会运行它,当提交按钮被点击时,选中的bool变成true,反过来,一个检查这个布尔值的if语句运行并显示图像。
但是,我想在显示3秒后删除此gif。我尝试使用StopWatch类,但当我尝试它时不起作用(SO上有人提到您需要一个Timer用于Blazor应用程序),所以我求助于使用Timer
在这种情况下,问题在于应用程序会停止运行。

@using blazorTestApp.Client.Entities
@using System.Timers
@code
{
    Timer timer = new Timer();
    public Books CreatedBook {get; set;} = new Books();
    bool check = false;
    public void OnSubmit()
    {
        check = true;
    }
}

@if(check)
{
    <img class="Thanks" src="https://gifsec.com/wp-content/uploads/2022/09/thank-you-gif-1.gif"/>
    timer.Interval = 3000;
    timer.Start();
    timer.Elapsed += (Object sender, ElapsedEventArgs e) => check = false; StateHasChanged(); timer.Stop();  
}
icomxhvb

icomxhvb1#

你不需要建立一个计时器,你可以使用内置的任务计时器一次延迟。这里是一个演示页面,显示一个警告框三秒,而不是你的图像。它显示了两种方式来设置延迟。对于简单的短时间等待使用简单。

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

@if(_loading)
{
    <div class="alert alert-info">Thanks for your business</div>
}

<div>
    <button class="btn btn-primary" disabled="@_loading" @onclick=OnLoad>Load Image</button>
    <button class="btn btn-dark" disabled="@_loading" @onclick=OnLoadAsync>Load Image</button>
</div>

@code {
    private bool _loading;

    // This way is simpler but means the task is "owned" by the Renderer
    // and the UI task doesn't complete until the delay is complete
    private async Task OnLoadAsync()
    {
        _loading = true;
        await Task.Delay(3000);
        _loading = false;
    }

    private Task _showTask = Task.CompletedTask;

    // This way hands off the wait to a task so the Ui task completes immediately 
    // and the Task is owned by the component
    private Task OnLoad()
    {
        // assign the load task to _showTask but don't await it.
        _showTask = LoadTaskAsync(3000);
        return Task.CompletedTask;
    }

    private async Task LoadTaskAsync(int millisecs)
    {
        _loading = true;
        StateHasChanged();
        await Task.Delay(millisecs);
        _loading = false;
        StateHasChanged();
    }
}

相关问题