MiniTimer
本文最后更新于 147 天前,其中的信息可能已经有所发展或是发生改变。
using System;
using System.Diagnostics;
using System.Threading;

public class MiniTimer
{
    private bool enabled;
    private Thread thread;
    private readonly AutoResetEvent are = new(false);
    private readonly Stopwatch stopwatch = new();

    public event EventHandler Elapsed;

    public bool Enabled
    {
        get => enabled;
        set
        {
            enabled = value;
            if (enabled)
                StartTimer();
            else
                StopTimer();
        }
    }

    public int Interval { get; set; }

    public bool IsRunning => thread != null && thread.IsAlive;

    public void Start() => Enabled = true;

    public void Stop() => Enabled = false;

    public void Wait() => thread?.Join();

    public void StopAndWait()
    {
        Stop();
        Wait();
    }

    private void StartTimer()
    {
        if (!IsRunning)
        {
            thread = new Thread(TimerThread);
            thread.Start();
        }
    }

    private void StopTimer()
    {
        if (IsRunning)
        {
            are.Set();
        }
    }

    private void TimerThread()
    {
        while (enabled)
        {
            stopwatch.Restart();
            Elapsed?.Invoke(this, EventArgs.Empty);
            are.WaitOne(Math.Max(Interval - (int)stopwatch.ElapsedMilliseconds, 0));
        }
    }
}
作者:AlexSJC
本文采用 CC BY-NC-ND 4.0 许可协议
暂无评论

发送评论 编辑评论


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇