在我的 Blazor 服务器端应用程序中,我有一个范围服务,它正在从远程 PLC 循环读取过程值。通过下面的代码,我尝试在我的剃刀页面上实时显示该值。但只显示一个值(未实现,尽管该值是动态变化的)。数据似乎没有从服务正确传输到剃刀页面。可能是什么问题:
我的范围服务代码:(Data_reader_service)
public void read_data_cyclic()
{
try
{
for(int y=0; y<10; y++)
{
//here I am reading process value from a remote PLC cyclic to the var. item_value. I can verify that the values are read by writing to a log file.
using (StreamWriter sw2 = File.AppendText(log_path))
{
sw2.WriteLine("val-"+y+":"+item_value+" "+Convert.ToString(DateTime.Now));
}
// here I pass the values to the event handler
Pass_item(item_value);
Thread.Sleep(1000);
// next cycle data reading
}
catch
{
//Error handling;
}
}
public string Pass_item(string new_item)
{
Item_Changed?.Invoke(Item_Changed, new_item);
return new_item;
}
public event EventHandler<string> Item_Changed;
我的剃刀页面的代码(当我单击按钮时,服务将开始读取数据)
@inject Data_reader_service Data_reader_service
<table>
<tr>
<td>
<button @onclick="call_read_data_service">
</button>
</td>
<td>@item_value</td>
</tr>
</table>
我的razor页面的cs代码:
public async Task call_read_data_service()
{
await Task.Run(() => Data_reader_service.read_data_cyclic());
//this time I have set for to be sure that the service has connected to remote PLC and started to read data
Thread.Sleep(5000);
Data_reader_service.Item_Changed += Item_Changed;
}
string item_value;
private async void Item_Changed(object sender, string new_item)
{
await InvokeAsync(() =>
{
// Set the local counter variable
item_value = new_item;
// Tell Blazor to rewrite the DOM
StateHasChanged();
});
}
我注意到我只检查了一次 razor.cs 代码中的值更改。 我更改了我的 razor.cs 代码,如下所示,它起作用了:
// I added a Timer
public System.Timers.Timer timer1 = new System.Timers.Timer();
public async Task call_read_data_service()
{
timer1.Elapsed += new ElapsedEventHandler(OnTimedEvent1);
timer1.Interval = 1000;
timer1.Enabled = true;
await Task.Run(() => Data_reader_service.read_data_cyclic());
}
// Checked the Item_Changed event every second
public void OnTimedEvent1(object source, ElapsedEventArgs e)
{
Data_reader_service.Item_Changed += Item_Changed;
}
string item_value;
private async void Item_Changed(object sender, string new_item)
{
await InvokeAsync(() =>
{
// Set the local counter variable
item_value = new_item;
// Tell Blazor to rewrite the DOM
StateHasChanged();
});
}