C# counter to count up to a target number

…衆ロ難τιáo~ 提交于 2021-01-07 01:22:07

问题


I'm trying to find out if anyone knows about an already existing c# plugin that will count up to a target number at a specified speed.

I'd like to be able to specify:

  • The start number
  • The end number
  • The amount of time it should take to get from start to end.
  • A custom callback function that can execute when a counter is finished.

I found these plugins one for javascript and one for asp.net:

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

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

I am making an application with asp.net core and blazor, I need something that fits blazor since it is a new technology and there is not much information on how to implement javascript plugins

if they had any example of how to implement countup.js in asp.net core they would help me a lot


回答1:


You can create a timer service that can serve you on many occasions:

Create the service class:

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;
    }

Add the service to the DI container, in the Program.Main method, as transient:

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

Usage

@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;
}

}



来源:https://stackoverflow.com/questions/65028123/c-sharp-counter-to-count-up-to-a-target-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!