Javascript 的 SetTimeout、SetInterval 和 ClearInterval 在 c# 中的等价物

标签 javascript c#

在许多情况下,我需要在 C# 中使用这些函数。我的项目必须是 .NET 4.0,下面的代码是我在阅读有关这些功能的问题和答案后能够编写的结果。我已经使用它们一段时间了,没有遇到任何问题。但是,玩线程很危险,所以我怀疑我是否做错了。

我的问题是,这些功能可以安全使用吗?还是有更好的方法来为 .NET 4.0 做这件事?

        private static volatile List<System.Threading.Timer> _timers = new List<System.Threading.Timer>();
        private static object lockobj = new object();
        public static void SetTimeout(Action action, int delayInMilliseconds)
        {
            System.Threading.Timer timer = null;
            var cb = new System.Threading.TimerCallback((state) =>
            {
                lock (lockobj)
                    _timers.Remove(timer);
                timer.Dispose();
                action();
            });
            lock (lockobj)
                _timers.Add(timer = new System.Threading.Timer(cb, null, delayInMilliseconds, System.Threading.Timeout.Infinite));
        }
        private static volatile Dictionary<Guid, System.Threading.Timer> _timers2 = new Dictionary<Guid, System.Threading.Timer>();
        private static object lockobj2 = new object();
        public static Guid SetInterval(Action action, int delayInMilliseconds)
        {
            System.Threading.Timer timer = null;
            var cb = new System.Threading.TimerCallback((state) => action());
            lock (lockobj2)
            {
                Guid guid = Guid.NewGuid();
                _timers2.Add(guid, timer = new System.Threading.Timer(cb, null, delayInMilliseconds, delayInMilliseconds));
                return guid;
            }
        }
        public static bool ClearInterval(Guid guid)
        {
            lock (lockobj2)
            {
                if (!_timers2.ContainsKey(guid))
                    return false;
                else
                {
                    var t = _timers2[guid];
                    _timers2.Remove(guid);
                    t.Dispose();
                    return true;
                }
            }
        }

最佳答案

这就是我使用任务并行库 (TPL) 在 C# 中实现 Javascript 的 setTimeout 和 clearTimeout 函数的方式:

设置超时:

public CancellationTokenSource SetTimeout(Action action, int millis) {

    var cts = new CancellationTokenSource();
    var ct = cts.Token;
    _ = Task.Run(() => {
        Thread.Sleep(millis);
        if (!ct.IsCancellationRequested)
            action();
    }, ct);

    return cts;
}

清除超时:

public void ClearTimeout(CancellationTokenSource cts) {
    cts.Cancel();
}

使用方法:

...
using System.Threading;
using System.Threading.Tasks;
...

var timeout = SetTimeout(() => {

    Console.WriteLine("Will be run in 2 seconds if timeout is not cleared...");

}, 2000);

如果您想在操作运行前取消操作:

ClearTimeout(timeout);

关于Javascript 的 SetTimeout、SetInterval 和 ClearInterval 在 c# 中的等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40502596/

相关文章:

javascript - signinwithphonenumber 身份验证失败

javascript - 是否可以对在浏览器中运行的 JavaScript 进行沙箱处理?

javascript - 没有前导零的小数是有效的 JSON 吗?

javascript - 消除根范围摘要调用的抖动

c# - 遍历数组并组装一个字符串

javascript - CSS 动画 onClick

c# - 为什么在 vstest.console.exe 中进行测试时,dotnet vstest 返回 "No test is available in"?

c# - 如何修复无法确定属性类型 "System.Web.Services....."

c# - 将 javascript 数组传递给 c# 方法

c# - 输出未正确写入 CSV