winform C# 可取消的超时任务(时间精度高)

测试发现 Task.Delay 计时精度不够,C#中论计时,还是 Stopwatch 最精确,由于要切换线程,还要考虑创建线程消耗的时间,果断使用线程池,最后实现的代码如下:

class TaskUtil
    {
        /// <summary>
        /// 发出一个可取消的超时任务
        /// </summary>
        /// <param name="delay">超时时间</param>
        /// <param name="cts">用于超时前取消任务 cts.Cancel() </param>
        /// <param name="action">超时后执行的任务</param>
        //[MethodImpl(MethodImplOptions.AggressiveInlining)]//方法内联
        public static void PostCancelableAction(long delay, CancellationTokenSource cts, Action action)
        {
            //ThreadPool.GetAvailableThreads(out int workerThreads, out int completionPortThreads);
            //Print($"workerThreads={workerThreads}, completionPortThreads={completionPortThreads}");
            Print("启动任务");
            Stopwatch sw = Stopwatch.StartNew();
            //使用线程池能够减少切换线程的耗时(2ms左右)
            ThreadPool.QueueUserWorkItem((state) => {
                long timeDiff = sw.ElapsedMilliseconds;
                Print($"执行任务Action 启动耗时{timeDiff}ms");
                long timeout = delay - timeDiff;
                while (!cts.IsCancellationRequested)
                {
                    if (sw.ElapsedMilliseconds >= timeout) break;
                }
                sw.Stop();
                if (cts.IsCancellationRequested)
                {
                    Print("取消任务");
                }
                else
                {
                    Print("任务超时");
                    action?.Invoke();
                }
            });
        }

        public static async void Delay(int delay)
        {
            Print("Before delay");
            await Task.Delay(delay);
            Print("After delay");
        }

        //[MethodImpl(MethodImplOptions.AggressiveInlining)]//方法内联
        public static void Print(object msg)
        {
            Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff} - {msg}");
        }
    }

测试代码

TaskUtil.Print("Form1() - Before PostCancelableAction");
CancellationTokenSource cts = new CancellationTokenSource();
TaskUtil.PostCancelableAction(5, cts, () => {
    TaskUtil.Print("Form1() - 执行超时任务");
});
//cts.Cancel();
TaskUtil.Print("Form1() - After PostCancelableAction");

另外,如果要计时精度高的定时器,可以使用 winmm.dll 中的函数,代码(原始链接)如下

    public class MMTimer : IDisposable
    {
        //Lib API declarations
        [DllImport("Winmm.dll", CharSet = CharSet.Auto)]
        static extern uint timeSetEvent(uint uDelay, uint uResolution, TimerCallback lpTimeProc, UIntPtr dwUser, uint fuEvent);

        [DllImport("Winmm.dll", CharSet = CharSet.Auto)]
        static extern uint timeKillEvent(uint uTimerID);

        [DllImport("Winmm.dll", CharSet = CharSet.Auto)]
        static extern uint timeGetTime();

        [DllImport("Winmm.dll", CharSet = CharSet.Auto)]
        static extern uint timeBeginPeriod(uint uPeriod);

        [DllImport("Winmm.dll", CharSet = CharSet.Auto)]
        static extern uint timeEndPeriod(uint uPeriod);

        //Timer type definitions
        [Flags]
        public enum fuEvent : uint
        {
            TIME_ONESHOT = 0,      //Event occurs once, after uDelay milliseconds.
            TIME_PERIODIC = 1,
            TIME_CALLBACK_FUNCTION = 0x0000,  /* callback is function */
            //TIME_CALLBACK_EVENT_SET = 0x0010, /* callback is event - use SetEvent */
            //TIME_CALLBACK_EVENT_PULSE = 0x0020  /* callback is event - use PulseEvent */
        }

        //Delegate definition for the API callback
        delegate void TimerCallback(uint uTimerID, uint uMsg, UIntPtr dwUser, UIntPtr dw1, UIntPtr dw2);

        //IDisposable code
        private bool disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    Stop();
                }
            }
            disposed = true;
        }

        ~MMTimer()
        {
            Dispose(false);
        }

        /// <summary>
        /// The current timer instance ID
        /// </summary>
        uint id = 0;

        /// <summary>
        /// The callback used by the the API
        /// </summary>
        TimerCallback thisCB;

        /// <summary>
        /// The timer elapsed event
        /// </summary>
        public event EventHandler Timer;
        protected virtual void OnTimer(EventArgs e)
        {
            if (Timer != null)
                Timer(this, e);
        }

        public MMTimer()
        {
            //Initialize the API callback
            thisCB = CBFunc;
        }


        /// <summary>
        /// Stop the current timer instance (if any)
        /// </summary>
        public void Stop()
        {
            lock (this)
            {
                if (id != 0)
                {
                    timeKillEvent(id);
                    Debug.WriteLine("MMTimer " + id.ToString() + " stopped");
                    id = 0;
                }
            }
        }

        /// <summary>
        /// Start a timer instance
        /// </summary>
        /// <param name="ms">Timer interval in milliseconds</param>
        /// <param name="repeat">If true sets a repetitive event, otherwise sets a one-shot</param>
        public void Start(uint ms, bool repeat)
        {
            //Kill any existing timer
            Stop();

            //Set the timer type flags
            fuEvent f = fuEvent.TIME_CALLBACK_FUNCTION | (repeat ? fuEvent.TIME_PERIODIC : fuEvent.TIME_ONESHOT);

            lock (this)
            {
                id = timeSetEvent(ms, 0, thisCB, UIntPtr.Zero, (uint)f);
                if (id == 0)
                    throw new Exception("timeSetEvent error");
                Debug.WriteLine("MMTimer " + id.ToString() + " started");
            }
        }

        void CBFunc(uint uTimerID, uint uMsg, UIntPtr dwUser, UIntPtr dw1, UIntPtr dw2)
        {
            //Callback from the MMTimer API that fires the Timer event. Note we are in a different thread here
            OnTimer(new EventArgs());
        }
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 这个题目上来说非常抽象,因为只有一个单个字母"c",无法明确知道提问者的具体意图,也没有明确的背景信息。所以我只能提供一些关于字母"c"的常见用法和相关描述: 1. 字母"c"是英语字母表的第三个字母,大写形式为"C"。 2. 字母"c"在计算机科学中也常用作变量名或函数名,代表着某个具体的值或操作。 3. 在化学元素周期表中,"C"指代碳元素,是一种非金属元素,常见于有机化合物和生命体中。 4. 字母"c"在音乐领域中是一个音符(C音),是音阶的第一音。 5. 在代数学中,"c"经常用作常数的代号,例如在一些方程或函数中。 6. 在网球比赛的记分板上,字母"c"代表"chase",意为“追求”,表示在比赛中选择继续追逐胜利的选项。 总之,对于这个问题,由于缺乏背景信息,很难准确理解提问者的意图。以上是一些关于字母"c"的常见用法和描述,希望能对您有所帮助。如果问题有具体需求,请提供更多信息,以便给出更精确的回答。 ### 回答2: c:c是计算机科学领域的一种编程语言,也是广泛使用的一种高级编程语言。它由Dennis Ritchie在20世纪70年代初在贝尔实验室开发出来,主要为UNIX操作系统的编写提供支持。后来,c语言逐渐流行起来,并成为一种通用的编程语言,被广泛应用于各种领域,如操作系统、嵌入式系统、游戏开发等。 c语言具有简洁、高效、灵活的特点,其语法结构类似于英语,使得程序员能够很容易地理解和使用。它提供了丰富的库函数和操作符,能够实现各种复杂的计算和逻辑操作。此外,c语言的代码可移植性好,可以在不同的平台上运行,这是其被广泛接受的一个重要原因。 c语言的学习和使用对于编程初学者来说是一个很好的起点。通过学习c语言,人们可以掌握编程的基本概念和技巧,培养解决问题和思考的能力。许多计算机科学专业的学生在大学时都需要学习c语言,并用它来完成一些实践性的编程任务。 总之,c语言是一门重要的编程语言,其简洁高效的特点以及广泛的应用领域使其在计算机科学领域中具有重要地位。无论是初学者还是专业人士,都可以通过学习和使用c语言来提高编程能力,并在各个领域中应用它来解决实际问题。 ### 回答3: c是英文字母表中的第三个字母,也是拉丁字母表中的一个字母。它的发音为/siː/,与“see”类似。c的形状像个弯曲的钩子,中间有一个凹点。在手写时,常常有一个起点、一个高点以及一个终点。c在英语中是一个常用字母,同时也被广泛用于其他语言中。 在数学中,c经常代表着数字100(罗马数字中的100为C),也代表着复数、圆周率π等概念。在化学中,c代表光速,即每秒299,792,458米。在计算机科学中,c是一种高级编程语言,被广泛用于软件开发。 另外,c还可以是一种音乐音符,代表着“低音do”的意思。在音乐乐谱中,c的位置比较靠下,发出的音调较低。 总的来说,c是一个非常常见的字母,它在各个领域中都有重要的作用。无论是在语言文字、数学、科学、计算机或音乐等方面,c都扮演着重要的角色。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值