首页 / C# / C#定期发射功能的正确方法
C#定期发射功能的正确方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#定期发射功能的正确方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2151字,纯文字阅读大概需要4分钟。
内容图文
![C#定期发射功能的正确方法](/upload/InfoBanner/zyjiaocheng/805/eec2a8b8a55843fd939cb1f05a227cf5.jpg)
我有大约20个函数,其中一些应该每秒触发一次,一些,每秒20次,另一次每分钟两次,目前我有这样的事情:
DateTime nowVar = DateTime.Now;
var lastExecutionFunc1 = nowVar;
var lastExecutionFunc2 = nowVar;
var lastExecutionFunc3 = nowVar;
var lastExecutionFunc4 = nowVar;
DateTime _now = DateTime.Now;
if ((_now - lastExecutionFunc1).TotalSeconds >= 0.1)
{
lastExecutionFunc1 = _now;
//dosomething
}
if ((_now - lastExecutionFunc2).TotalSeconds >= 0.5)
{
lastExecutionFunc2 = _now;
//do something else
}
if ((_now - lastExecutionFunc3).TotalSeconds >= 30)
{
lastExecutionFunc3 = _now;
//do something else
}
.....
虽然这有效,但我不禁想到应该有更优雅的方式来做到这一点.创建一个var来存储每个执行使得核心看起来非常混乱.猜猜我可以使用对,但这也不会太好.
有什么建议?
编辑:如果你想看到我想要完成的事情,you can see the whole code here.在第525行.
解决方法:
下面的代码提供了一个带有同步锁的基本调度程序
using System;
using System.Collections.Generic;
using System.Timers;
namespace TimerUsage
{
class Program
{
static void Main(string[] args)
{
Scheduler scheduler = new Scheduler();
scheduler.ScheduleMethod(100, () => Console.WriteLine("func1"));
scheduler.ScheduleMethod(200, () => Console.WriteLine("func2"));
scheduler.ScheduleMethod(300, () => Console.WriteLine("func3"));
scheduler.ScheduleMethod(1000, () => Console.WriteLine("func4"));
scheduler.Run();
System.Threading.Thread.Sleep(10000);
}
}
public class Scheduler
{
private Dictionary<int, Row> _schedule = new Dictionary<int, Row>();
public void ScheduleMethod(int interval, Action method)
{
Row row;
if (!_schedule.TryGetValue(interval, out row))
{
row = new Row(interval);
_schedule[interval] = row;
}
row.AddMethod(method);
}
public void Run()
{
foreach (var item in _schedule)
{
item.Value.StartTimer();
}
}
}
internal class Row
{
private object _syncLock = new object();
private Timer _timer;
private List<Action> _methods = new List<Action>();
public Row(int interval)
{
_timer = new System.Timers.Timer(interval);
_timer.Elapsed += ExecuteItems;
}
private void ExecuteItems(object sender, ElapsedEventArgs e)
{
lock (_syncLock)
{
foreach (var method in _methods)
{
method();
}
}
}
public void AddMethod(Action method)
{
_methods.Add(method);
}
public void StartTimer()
{
_timer.Start();
}
}
}
内容总结
以上是互联网集市为您收集整理的C#定期发射功能的正确方法全部内容,希望文章能够帮你解决C#定期发射功能的正确方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。