【问题标题】:C# counter to count up to a target numberC# 计数器计数到目标数
【发布时间】:2021-03-09 16:37:15
【问题描述】:

我正在尝试找出是否有人知道一个已经存在的 c# 插件,该插件将以指定的速度计数到目标数。

我希望能够指定:

  • 起始编号
  • 结束编号
  • 从开始到结束应该花费的时间。
  • 一个自定义的回调函数,可以在计数器运行时执行 完成。

我发现这些插件一个用于 javascript,一个用于 asp.net:

https://inorganik.github.io/countUp.js/

https://www.nuget.org/packages/Wisej-2-CountUp/

我正在使用 asp.net core 和 blazor 制作应用程序,我需要适合 blazor 的东西,因为它是一项新技术,并且没有太多关于如何实现 javascript 插件的信息

如果他们有任何关于如何在 asp.net 核心中实现 countup.js 的示例 他们会帮助我很多

【问题讨论】:

  • 请研究如何在 Blazor 中使用 npm 包。如果你知道了,rest 只是实现 countUp.js。
  • 我这是一个学校项目?
  • 感谢建议已经在 asp.net 核心中安装 npm 以与 blazor 一起使用
  • CountUp.js 使用缓动。如果需要,那么您最好的课程是围绕 js 的 Blazor 包装器。

标签: javascript c# asp.net-core blazor


【解决方案1】:

您可以创建一个可以在很多场合为您服务的计时器服务:

创建服务类:

public class BlazorTimer
    {
        private Timer _timer;

        internal void SetTimer(double interval)
        {
            _timer = new Timer(interval);
            _timer.Elapsed += NotifyTimerElapsed;
            _timer.Enabled = true;
            _timer.Start();
        }

        private void NotifyTimerElapsed(object sender, ElapsedEventArgs e)
        {
            OnElapsed?.Invoke();
        }

        public event Action OnElapsed;
    }

在 Program.Main 方法中将服务作为瞬态添加到 DI 容器中:

builder.Services.AddTransient(config =>
        {
            var blazorTimer = new BlazorTimer();
            blazorTimer.SetTimer(1000);
            return blazorTimer;
        });

用法

@page "/"

@implements IDisposable
@inject BlazorTimer Timer

@count.ToString()


@code{
private int count = 0;

protected override void OnInitialized()
{
    Timer.OnElapsed += NotifyTimerElapsed;

    base.OnInitialized();
}

private void NotifyTimerElapsed()
{
    // Note: WebAssembly Apps are currently supporting a single thread, which 
    // is why you don't have to call
    // the StateHasChanged method from within the InvokeAsync method. But it 
    // is a good practice to do so in consideration of future changes, such as 
    // ability to run WebAssembly Apps in more than one thread.
    InvokeAsync(() => { count++; StateHasChanged(); });
}

public void Dispose()
{
    Timer.OnElapsed -= NotifyTimerElapsed;
}

}

【讨论】:

  • @Henk Holterman:“从容器解析的服务不应该由开发人员处理。”您在哪里看到我的代码处理 BlazorTimer 服务?在 Blazor 组件中实现的 Dispose 方法中取消订阅事件处理程序绝不会释放 BlazorTimer 服务...请创建一个新问题,以便我对此进行扩展。
  • 不,你是对的。但是 BlazorTimer 正在泄漏 _timer。计时器是 IDisposable。
猜你喜欢
  • 1970-01-01
  • 2011-02-02
  • 2012-05-28
  • 1970-01-01
  • 2011-12-11
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多