我正在 Blazor 服务器端页面中设置计时器。目标是每 x 秒调用一次 API,并根据返回值更新 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();
}
Run Code Online (Sandbox Code Playgroud)
这效果很好。UI 每秒更新一次新的时间值。但是,我不知道如何调用异步任务来获取值。我想更换线路:
Time = DateTime.Now.ToString();
Run Code Online (Sandbox Code Playgroud)
一行调用以下函数:
private async Task<string> GetValue()
{
var result = await _api.GetAsync<StringDto>("/api/GetValue");
return result.Text;
}
Run Code Online (Sandbox Code Playgroud)
我试过这条线:
Time = GetValue().Result;
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
The current thread is not associated with the Dispatcher. Use InvokeAsync() to switch execution to …Run Code Online (Sandbox Code Playgroud)