Blazor (Mudblazor) Table Countdown Property

huangapple go评论68阅读模式
英文:

Blazor (Mudblazor) Table Countdown Property

问题

我有一个在MudBlazor应用程序中的表格,其中包含一个“停止时间”的值。我正在在表格中显示的一列是“剩余时间”,它是由一个函数填充的,该函数根据当前日期和“停止时间”值来计算剩余时间。我想知道是否有一种简单的方式来使这个值动态更新,比如每隔一分钟更新一次。目前的设置方式是您可以点击一个刷新按钮,但这样做会相当耗时,我不太想设置每分钟完全刷新的方式。

<MudTable Items="ActiveForwards" Hover="true" SortLabel="Sort By" Elevation="0" Filter="new Func<UniversalObject,bool>(FilterResults)">
    <ToolBarContent>
        <MudTextField @bind-Value="searchString1" Placeholder="Search" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"></MudTextField>
    </ToolBarContent>
    <HeaderContent>
        <MudTh><MudTableSortLabel InitialDirection="SortDirection.Ascending" SortBy="new Func<UniversalObject, object>(x=>x.DisplayName)">Mailbox</MudTableSortLabel></MudTh>
        <MudTh><MudTableSortLabel SortBy="new Func<UniversalObject, object>(x=>x.EmailAddress)">Email Address</MudTableSortLabel></MudTh>
        <MudTh><MudTableSortLabel SortBy="new Func<UniversalObject, object>(x=>x.User.ForwardToDisplay)">Forward Mailbox</MudTableSortLabel></MudTh>
        <MudTh><MudTableSortLabel SortBy="new Func<UniversalObject, object>(x=>x.User.StopTime.ToString())">Stop Time</MudTableSortLabel></MudTh>
        <MudTh>Time Left</MudTh>
        <MudTh></MudTh>
        <MudTh></MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd DataLabel="Display Name">@context.DisplayName</MudTd>
        <MudTd DataLabel="Email Address">@context.EmailAddress</MudTd>
        <MudTd DataLabel="Forward To Display Name">@context.User.ForwardToDisplay</MudTd>
        <MudTd DataLabel="Stop Time">@context.User.StopTime.ToString()</MudTd>
        <MudTd DataLabel="Time Left"><h3>@CountdownTimer(context)</h3></MudTd>
        <MudTd><MudIcon Icon="@Icons.Material.Filled.Refresh" Variant="Variant.Filled" Color="@(context.User.DeliverToMailboxAndForward ? Color.Primary : Color.Default)" Size="Size.Medium" /></MudTd>
        <MudTd DataLabel="Actions"><MudIconButton Icon="@Icons.Material.Filled.Delete" @onclick="() => HandleRemoveAction(context)"></MudIconButton></MudTd>
    </RowTemplate>
    <PagerContent>
        <MudTablePager PageSizeOptions="new int[]{10, 50, 100}" />
    </PagerContent>
</MudTable>
private string CountdownTimer(UniversalObject forward)
{
    if (forward.User.StopTime != null)
    {
        var timeLeft = forward.User.StopTime - DateTime.Now;

        if (timeLeft.Value.Days > 0)
        {
            return $"{timeLeft.Value.Days}D {timeLeft.Value.Hours}H {timeLeft.Value.Minutes}M";
        }
        if (timeLeft.Value.Hours > 0)
        {
            return $"{timeLeft.Value.Hours}H {timeLeft.Value.Minutes}M";
        }
        return $"{timeLeft.Value.Minutes}M";
    }
    return "∞";
}
英文:

I have a table in a MudBlazor application that contains a value for Stop Time. One of the columns I am displaying on the table is Time Left which is populated by a function that calculates the time left based on the current date and the Stop Time value. I am wondering if there is an easy way to make this value update dynamically, say once every minute. The way I have it setup now you can hit a refresh button, but it is quite taxing and I don't really want to setup a full refresh every minute.

 &lt;MudTable Items=&quot;ActiveForwards&quot; Hover=&quot;true&quot; SortLabel=&quot;Sort By&quot; Elevation=&quot;0&quot; Filter=&quot;new Func&lt;UniversalObject,bool&gt;(FilterResults)&quot;&gt;
&lt;ToolBarContent&gt;
&lt;MudTextField @bind-Value=&quot;searchString1&quot; Placeholder=&quot;Search&quot; Adornment=&quot;Adornment.Start&quot; AdornmentIcon=&quot;@Icons.Material.Filled.Search&quot; IconSize=&quot;Size.Medium&quot; Class=&quot;mt-0&quot;&gt;&lt;/MudTextField&gt;
&lt;/ToolBarContent&gt;
&lt;HeaderContent&gt;
&lt;MudTh&gt;&lt;MudTableSortLabel InitialDirection=&quot;SortDirection.Ascending&quot; SortBy=&quot;new Func&lt;UniversalObject, object&gt;(x=&gt;x.DisplayName)&quot;&gt;Mailbox&lt;/MudTableSortLabel&gt;&lt;/MudTh&gt;
&lt;MudTh&gt;&lt;MudTableSortLabel SortBy=&quot;new Func&lt;UniversalObject, object&gt;(x=&gt;x.EmailAddress)&quot;&gt;Email Address&lt;/MudTableSortLabel&gt;&lt;/MudTh&gt;
&lt;MudTh&gt;&lt;MudTableSortLabel SortBy=&quot;new Func&lt;UniversalObject, object&gt;(x=&gt;x.User.ForwardToDisplay)&quot;&gt;Forward Mailbox&lt;/MudTableSortLabel&gt;&lt;/MudTh&gt;
&lt;MudTh&gt;&lt;MudTableSortLabel SortBy=&quot;new Func&lt;UniversalObject, object&gt;(x=&gt;x.User.StopTime.ToString())&quot;&gt;Stop Time&lt;/MudTableSortLabel&gt;&lt;/MudTh&gt;
&lt;MudTh&gt;Time Left&lt;/MudTh&gt;
&lt;MudTh&gt;&lt;/MudTh&gt;
&lt;MudTh&gt;&lt;/MudTh&gt;
&lt;/HeaderContent&gt;
&lt;RowTemplate&gt;
&lt;MudTd DataLabel=&quot;Display Name&quot;&gt;@context.DisplayName&lt;/MudTd&gt;
&lt;MudTd DataLabel=&quot;Email Address&quot;&gt;@context.EmailAddress&lt;/MudTd&gt;
&lt;MudTd DataLabel=&quot;Forward To Display Name&quot;&gt;@context.User.ForwardToDisplay&lt;/MudTd&gt;
&lt;MudTd DataLabel=&quot;Stop Time&quot;&gt;@context.User.StopTime.ToString()&lt;/MudTd&gt;
&lt;MudTd DataLabel=&quot;Time Left&quot;&gt;&lt;h3&gt;@CountdownTimer(context)&lt;/h3&gt;&lt;/MudTd&gt;
&lt;MudTd&gt;&lt;MudIcon Icon=&quot;@Icons.Material.Filled.Refresh&quot; Variant=&quot;Variant.Filled&quot; Color=&quot;@(context.User.DeliverToMailboxAndForward ? Color.Primary : Color.Default)&quot; Size=&quot;Size.Medium&quot; /&gt;&lt;/MudTd&gt;
&lt;MudTd DataLabel=&quot;Actions&quot;&gt;&lt;MudIconButton Icon=&quot;@Icons.Material.Filled.Delete&quot; @onclick=&quot;() =&gt; HandleRemoveAction(context)&quot;&gt;&lt;/MudIconButton&gt;&lt;/MudTd&gt;
&lt;/RowTemplate&gt;
&lt;PagerContent&gt;
&lt;MudTablePager PageSizeOptions=&quot;new int[]{10, 50, 100}&quot; /&gt;
&lt;/PagerContent&gt;
&lt;/MudTable&gt;

}

private string CountdownTimer(UniversalObject forward)
{
if (forward.User.StopTime != null)
{
var timeLeft = forward.User.StopTime - DateTime.Now;
if (timeLeft.Value.Days &gt; 0)
{
return $&quot;{timeLeft.Value.Days}D {timeLeft.Value.Hours}H {timeLeft.Value.Minutes}M&quot;;
}
if (timeLeft.Value.Hours &gt; 0)
{
return $&quot;{timeLeft.Value.Hours}H {timeLeft.Value.Minutes}M&quot;;
}
return $&quot;{timeLeft.Value.Minutes}M&quot;;
}
return &quot;\u221e&quot;;
}

答案1

得分: 0

以下是您要翻译的内容:

"Firstly,
don't run Task.Run unless you have a very specific reason to do so (and understand why). You can quickly get into trouble. Code that interacts with the UI has to run within the UI context thread. Take this case: the application has switched the timer task to a separate threadpool thread. Try calling StateHasChanged directly in the handler.

private async void OnTimerElapsed(object? sender, ElapsedEventArgs e)
{
    await this.RefreshData();
}

private Task RefreshData()
{
    this.Message = DateTime.Now.ToLongTimeString();
    this.StateHasChanged();
    return Task.CompletedTask;
}

Run the application without debug and it crashes. Run in debug mode and you get:

The current thread is not associated with the Dispatcher. Use InvokeAsync() to switch execution to the Dispatcher when triggering rendering or component state."
Update `RefreshData`:
```csharp
private async Task RefreshData()
{
    this.Message = DateTime.Now.ToLongTimeString();
    await this.InvokeAsync(StateHasChanged);
}
``` and `await this.InvokeAsync(StateHasChanged)` ensures that `StateHasChanged` is run on the `Dispatcher` thread.

Secondly,
`_timer.Elapsed` is an event. It's fire and forget. The return type for any event handler is `void`. If you need to run any async code, you declare it as `async`. It becomes a `Task` without an owner, so its ownership defaults to the application. Any exceptions are bubbled up to the application and crash it. You've seen exactly that where `StateHasChanged` was run on the wrong thread and crashed the application.
Go back to the original `OnTimerElapsed` with the direct call to `StateHasChanged`:
```csharp
private void OnTimerElapsed(object? sender, ElapsedEventArgs e)
    => _refreshTask = this.RefreshData();
private Task RefreshData()
{
    this.Message = DateTime.Now.ToLongTimeString();
    this.StateHasChanged();
    return Task.CompletedTask;
}

Run the application without debug, and while the counter doesn't update, it doesn't crash: you can navigate to other pages,... Run in debug mode, and you'll get the exception (because the debugger traps exceptions).

A modification to the original code
Whilst writing this explanation, I realized you use this pattern for all event handlers in the UI to ensure the handler gets run on the UI/Dispatcher thread.

private void OnTimerElapsed(object? sender, ElapsedEventArgs e)
    => _refreshTask = InvokeAsync(this.RefreshData);

So the new version looks like this:

private void OnTimerElapsed(object? sender, ElapsedEventArgs e)
    => _refreshTask = InvokeAsync(this.RefreshData);
private Task RefreshData()
{
    this.Message = DateTime.Now.ToLongTimeString();
    this.StateHasChanged();
    return Task.CompletedTask;
}
```"

<details>
<summary>英文:</summary>

Here&#39;s a simple demo page that shows how to run a timer Task in a page.

```csharp
@page &quot;/&quot;
@using System.Timers
@implements IDisposable

&lt;PageTitle&gt;Index&lt;/PageTitle&gt;

&lt;h1&gt;Hello, world!&lt;/h1&gt;

Welcome to your new app.

&lt;div class=&quot;alert alert-info&quot;&gt;
    @this.Message
&lt;/div&gt;

@code {
    private System.Timers.Timer _timer = new System.Timers.Timer(2000);
    private Task _refreshTask = Task.CompletedTask;
    private string? Message;

    protected override void OnInitialized()
    {
        _timer.AutoReset = true;
        _timer.Elapsed += this.OnTimerElapsed;
        _timer.Enabled = true;

        _refreshTask = this.RefreshData();
    }

    private void OnTimerElapsed(object? sender, ElapsedEventArgs e)
        =&gt; _refreshTask = InvokeAsync(this.RefreshData);

    private Task RefreshData()
    {
        this.Message = DateTime.Now.ToLongTimeString();
        this.StateHasChanged();
        return Task.CompletedTask;
    }

    public void Dispose()
        =&gt; _timer.Elapsed -= this.OnTimerElapsed;

}

You've questioned the reason for _refreshTask = this.RefreshData(); and replaced it with:

 Task.Run(RefreshData);

Firstly,

don't run Task.Run unless you have a very specific reason to do so (and understand why). You can quickly get into trouble. Code that interacts with the UI has to run within the UI context thread. Take this case: the application has switched the timer task to a separate threadpool thread. Try calling StateHasChanged directly in the handler.

private async void OnTimerElapsed(object? sender, ElapsedEventArgs e)
{
    await this.RefreshData();        
}

private Task RefreshData()
{
    this.Message = DateTime.Now.ToLongTimeString();
    this.StateHasChanged();
    return Task.CompletedTask;
}

Run the application without debug and it crashes. Run in debug mode and you get:

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

Update RefreshData:

private async Task RefreshData()
{
    this.Message = DateTime.Now.ToLongTimeString();
    await this.InvokeAsync(StateHasChanged);
}

and await this.InvokeAsync(StateHasChanged) ensures that StateHasChanged is run on the Dispatcher thread.

Secondly,

_timer.Elapsed is a event. It's fire and forget. The return type for any event hanlder is void. If you need to run any async code you declare it as async. It becomes a Task without an owner, so it's ownership defaults to the application. Any exceptions are bubbled up to the application and crash it. You've seen exacly that where StateHasChanged was run on the wrong thread and crashed the application.

Go back to the original OnTimerElapsed with the direct call to StateHasChanged:

    private void OnTimerElapsed(object? sender, ElapsedEventArgs e)
        =&gt; _refreshTask = this.RefreshData();

    private Task RefreshData()
    {
        this.Message = DateTime.Now.ToLongTimeString();
        this.StateHasChanged();
        return Task.CompletedTask;
    }

Run the application without debug and while the counter doesn't update, it doesn't crash: you can navigate to other pages,... Run in debug mode and you'll get the exception (because the debugger traps exceptions).

A modification to the original code

Whilst writing this explanation I realised you use this pattern for all event handlers in the UI to ensure the handler gets run on UI/Dispatcher thread.

    private void OnTimerElapsed(object? sender, ElapsedEventArgs e)
        =&gt; _refreshTask = InvokeAsync(this.RefreshData);

So the new version looks like this:

    private void OnTimerElapsed(object? sender, ElapsedEventArgs e)
        =&gt; _refreshTask = InvokeAsync(this.RefreshData);

    private Task RefreshData()
    {
        this.Message = DateTime.Now.ToLongTimeString();
        this.StateHasChanged();
        return Task.CompletedTask;
    }

huangapple
  • 本文由 发表于 2023年3月12日 13:56:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711301.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定