我正在实施一项预定的工作,例如方法,并已缩小到方法范围。一种实现计时器间隔,另一种基于任务延迟。
我还考虑过使用 Azure 计时器触发的 Web 作业,但它们不能在多实例模式下工作。实际上,在多实例应用程序中,其中一个实例中仅触发一个触发器,而其他实例则被锁定,因此增加应用程序的实例计数不会增加触发的事件数量。
方法 A(定时器间隔)
using System;
using System.Threading.Tasks;
using System.Timers;
public class Example
{
public static void Main()
{
var aTimer = new Timer();
aTimer.Interval = 5000;
aTimer.Elapsed += OnTimedEventA;
aTimer.AutoReset = true;
aTimer.Enabled = true;
var bTimer = new System.Timers.Timer();
bTimer.Interval = 2000;
bTimer.Elapsed += OnTimedEventB;
bTimer.AutoReset = true;
bTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program at any time... ");
Console.ReadLine();
}
private static void OnTimedEventA(Object source, System.Timers.ElapsedEventArgs e)
{
Task.Run(() =>
{
Console.WriteLine("The Elapsed event A was raised at {0}", DateTime.Now);
});
}
private static void OnTimedEventB(Object source, System.Timers.ElapsedEventArgs e)
{
Task.Run(() =>
{
Console.WriteLine("The Elapsed event B was raised at {0}", DateTime.Now);
});
}
}
方法 B(任务延迟)
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
EventAAsync();
EventBAsync();
Console.WriteLine("Press the Enter key to exit the program at any time... ");
Console.ReadLine();
}
private static async Task EventAAsync()
{
while (true)
{
Task.Run(() =>
{
Console.WriteLine("The Elapsed event A was raised at {0}", DateTime.Now);
});
await Task.Delay(TimeSpan.FromSeconds(5));
}
}
private static async Task EventBAsync()
{
while (true)
{
Task.Run(() =>
{
Console.WriteLine("The Elapsed event B was raised at {0}", DateTime.Now);
});
await Task.Delay(TimeSpan.FromSeconds(2));
}
}
}
方法 A 和方法 B 的功能相同。
他们都以 5 秒和 2 秒的固定间隔调用火灾事件 A 和 B,然后忘记了。现在我正在尝试了解这两种方法的优缺点。最后,事件本身在单独的线程上运行。理论上和实践中,应该采用两者中的哪一个来处理许多此类跨多个实例扩展的事件触发器。
也欢迎任何其他方法。
Method A当您必须定期触发某些任务时使用。Method B当您必须在某些任务的触发之间提供定期间隔时使用。
如果事件处理程序(触发器后执行的任务)需要更长的时间来处理,则存在差异。
方法一:无论事件处理程序中的任务花费多少时间,事件处理程序都会以设置的时间间隔持续触发(代码必须是可重入的)。
方法B:任务完成然后我们睡觉。因此,如果任务需要不同的时间来完成,则下一次触发也会在不同的时间
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)