2017-01-16 31 views
3

定时器ASP.NET核心之前,我用来实现这样的计时器:如何实现与.NETCoreApp1.1

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控制台应用程序和系统同样需要。使用ASP.NET Core的定时器不再存在。我也尝试使用System.Threading.Timer,但该项目不再构建。

我该如何使用.NETCoreApp1.1实现Timer?有没有相当于System.Timers?

+0

System.Threading.Timer不支持.NET的核心> = 1.1.0请参阅相关性[第(https://www.nuget.org/ packages/System.Threading.Timer /) – Sanket

+0

@Sanket它是兼容的,但我必须添加一个依赖到Microsoft.NETCore.App框架部分 – AdrienTorris

回答

5

好了,所以要实现定时器与.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" 
    } 
    } 
}