0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# メモ

0
Posted at

using System;
using System.Threading.Tasks;

public sealed class Timer
{
    private Action _action;
    private int _ms;
    private bool _setsTime;
    private bool _setsAction;
    private bool _excecuteStartAsyncBefore;

    public void SetTime(int ms)
    {
        CheckSetsTimeYet();
        _setsTime = true;
        _ms = ms;
    }

    public void SetAction(Action action)
    {
        CheckSetsActionYet();
        _setsAction = true;
        _action = action;
    }

    public async void StartAsync()
    {
        CheckReady();

        _excecuteStartAsyncBefore = true;
        await Task.Delay(_ms);
        Fire();
    }

    private void Fire()
    {
        _action.Invoke();
    }

    private void CheckReady()
    {
        CheckSetNeccesaryValues();
        CheckFirstExcecte();
    }

    private void CheckSetNeccesaryValues()
    {
        if (!_setsTime || !_setsAction)
            throw new Exception("Set Time and Action");
    }

    private void CheckFirstExcecte()
    {
        if (_excecuteStartAsyncBefore)
            throw new Exception("Not first execute");
    }

    private void CheckSetsTimeYet()
    {
        if (_setsTime)
            throw new Exception("Already Set Time");
    }

    private void CheckSetsActionYet()
    {
        if (_setsAction)
            throw new Exception("Already Set Action");
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?