当我重复调用作用域服务(即输出值)时,我的 Blazor 服务器端 razor 页面中的值不会更新。为什么?

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

我有以下 razor.cs 代码,该代码正在调用作用域服务中的函数。作用域服务中的函数正在从 REST API 读取动态变化的过程值。当我在 razor.cs 页面中调用该函数时,我可以毫无问题地读取该值。

当我重复调用该函数(循环)时:我看到服务函数中的值每次都正确更改(来自日志)。 但剃刀页面上的值仅显示第一个读取的值,并且不会在下一个函数调用中实现。可能出了什么问题?

我的剃须刀页面代码:

 <table>
   <tr>                    
     <td >Process item</td>
     <td >@value_screen</td>
   </tr>
 </table>

我的razor.cs代码:

 public string value_screen=""; 
 public async Task Read_value_from_scoped_service()
 {
   for(int i=0; i<10; i++)
   {
   value_screen = await Task.Run(() => Service_API.Read_Process_value(url));
   StateHasChanged();         
   Thread.Sleep(1000);
   }
 }

我在范围服务(Service_API)中的函数:

 public string value_from_API="";
 public string Read_Process_value(string url)
 {
   // some code that delivers the value from a API
     using (StreamWriter sw = File.AppendText(logpath))
     {
       sw.WriteLine("item_valuer= " + value_screen + " " + Convert.ToString(DateTime.Now));
       // in the logfile i can see the updated 10 values for each call
     }
   return value_from_API;
 }
service blazor-server-side razor-pages scoped
1个回答
0
投票

从您的代码中不清楚您实际显示的内容如何插入在一起。

这是我为其他人编写的演示,我认为它提供了一个供您使用的模板。

这是我的数据提供者。它不是服务,因为它不需要。

public class WeatherGaugeProvider
{
    private TaskCompletionSource<int> _tcs = new TaskCompletionSource<int>();

    private WeatherGaugeProvider() { }

    public static  Task<int> GetTemperatureAsync()
    {
        var gauge = new WeatherGaugeProvider();

        ThreadPool.QueueUserWorkItem(_ =>
        {
            // Your code to get the data
            // this just emulates that
            Thread.Sleep(250);
            gauge._tcs.SetResult(Random.Shared.Next(-40, 60));
        });
        return gauge._tcs.Task;
    }
}

我的主页使用计时器每秒获取数据。

@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.
<div class="mb-3">
    <button disabled="@_isRunning" class="btn btn-primary" @onclick="this.GetDataAsync">Get Values</button>
    <button disabled="@(!_isRunning)" class="btn btn-danger" @onclick="this.StopTimer">Stop</button>
</div>

<div class="bg-dark text-white m-2 p-2">
    <pre>Temperature : @_temperature</pre>
</div>

@code {
    private int _temperature;
    private Timer? _timer;
    private bool _isRunning => _timer is not null;

    private Task GetDataAsync()
    {
        _timer = new(OnTimerElasped, null, 0, 1000);
        return Task.CompletedTask;
    }

    private void StopTimer()
    {
        _timer?.Dispose();
        _timer = null;
    }

    private async void OnTimerElasped(object? state)
    {
        _temperature = await WeatherGaugeProvider.GetTemperatureAsync();
        await this.InvokeAsync(StateHasChanged);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.