在ASP.NET Core之前,我曾经实现过这样的计时器:
public class Class1 { Timer tm = null; public Class1() { this.tm.Elapsed += new ElapsedEventHandler(Timer_Elapsed); this.tm.AutoReset = true; this.tm = new Timer(60000); } protected void Timer_Elapsed(object sender, ElapsedEventArgs e) { this.tm.Stop(); try { // My business logic here } catch (Exception) { throw; } finally { this.tm.Start(); } } }
我对.NETCoreApp1.1控制台应用程序有同样的需求,并且System.Timers不再存在于ASP.NET Core中.我也尝试使用System.Threading.Timer,但项目不再构建.
如何使用.NETCoreApp1.1实现Timer?是否有相当于System.Timers?
好的,要使用.NETCoreApp1.0或.NETCoreApp1.1实现计时器,必须使用System.Threading.Timer.它几乎像System.Timers一样工作,你有这里的所有文档:https://msdn.microsoft.com/en-us/library/system.threading.timer(v=vs.110).aspx
如果在添加System.Threading.Timer包之后您的项目不再构建,那是因为您必须将平台版本的Microsoft.NETCore.App添加到您的netcoreapp框架:
{ "version": "1.0.0-*", "buildOptions": { "emitEntryPoint": true }, "dependencies": { "System.Threading.Timer": "4.3.0" }, "frameworks": { "netcoreapp1.1": { "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.1.0" } }, "imports": "dnxcore50" } } }