Blazor Timer调用异步API任务以更新UI [英] Blazor Timer call async API task to update UI

查看:1004
本文介绍了Blazor Timer调用异步API任务以更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Blazor服务器端页面中设置一个计时器.目标是每x秒调用一次API,并根据返回值更新UI.

I am setting up a timer in a Blazor server-side page. The goal is to call an API every x seconds and based on the return value, update the UI.

我得到了以下代码:

private string Time { get; set; }

protected override void OnInitialized()
{
    var timer = new System.Threading.Timer((_) =>
    {
        Time = DateTime.Now.ToString();
        InvokeAsync(() =>
        {
            StateHasChanged();
        });
    }, null, 0, 1000);
    base.OnInitialized();
}

这很漂亮.用户界面每秒更新一次新的时间值.但是,我不知道如何调用异步任务来获取值.我想替换一行:

This works beautifully. The UI was updated every second with the new time value. However, I can't figure out how to call an async task to get the value. I would like to replace the line:

Time = DateTime.Now.ToString();

带有一行调用以下函数的行:

with a line that calls the following function:

private async Task<string> GetValue()
{
    var result = await _api.GetAsync<StringDto>("/api/GetValue");
    return result.Text;
}

我已经尝试过这一行:

Time = GetValue().Result;

但是我收到以下错误:

The current thread is not associated with the Dispatcher. Use InvokeAsync() to switch execution to the Dispatcher when triggering rendering or component state.

调用异步方法需要做什么?

What do I need to do to call the async method?

感谢一堆!

推荐答案

尝试以下代码:

  private string Time { get; set; }

protected override void OnInitialized()
{
    base.OnInitialized();
    var timer = new System.Threading.Timer((_) =>
    {

        InvokeAsync( async ()  =>
        {
            Time = await GetValue();
            StateHasChanged();
        });
    }, null, 0, 1000);

}

您的GetValue方法应为:

Your GetValue method should be:

private async Task<string> GetValue()
{
    return await _api.GetAsync<StringDto>("/api/GetValue");
  
}

这篇关于Blazor Timer调用异步API任务以更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆