【问题标题】:How implement a timer with .NETCoreApp1.1如何使用 .NETCoreApp1.1 实现计时器
【发布时间】:2017-05-31 04:24:14
【问题描述】:

在 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 的等价物?

【问题讨论】:

  • System.Threading.Timer 确实支持 .NET core >= 1.1.0 参考依赖section
  • @Sanket 它是兼容的,但我必须在 Framework 部分添加对 Microsoft.NETCore.App 的依赖项

标签: c# timer asp.net-core-1.1


【解决方案1】:

好的,所以要使用 .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"
    }
  }
}

【讨论】:

    猜你喜欢
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多