我有开发Windows服务的经验,其中使用不同的计时器为不同的时间间隔执行不同的方法。但是我最近遇到了一个使用System.Threading.Tasks和ManualResetEvent做同样事情的Windows服务。我对这些知之甚少。以下是演示如何创建Windows服务的代码。我只包含了onstart和执行的方法。我检查了控制台应用程序,因为waitone而没有阻止任务。但正如我所说,我对任务没有太多的技术知识,所以我需要一些意见,对于不同方法在不同的时间间隔执行窗口服务,以下方法是正确还是错误。
Private Shared mReset As New ManualResetEvent(False)
Protected Overrides Sub OnStart(ByVal args() As String)
Try
mReset.Reset()
Dim task1 As Task = Task.Factory.StartNew(New Action(AddressOf Task1), TaskCreationOptions.PreferFairness)
Dim task2 As Task = Task.Factory.StartNew(New Action(AddressOf Task2), TaskCreationOptions.PreferFairness)
Catch ex As Exception
'Throw ex
WriteMessage(ex.Message)
End Try
End Sub
Private Sub Task1()
Try
Dim WaitTime As Integer = 24 * 60 * 60 * 1000
While Not mReset.WaitOne(WaitTime)
Try
' Perform Some Task Daily
Catch ex As Exception
WriteMessage(ex.Message)
WriteMessage(ex.StackTrace.ToString)
End Try
End While
Catch ex As Exception
WriteMessage(ex.Message)
WriteMessage(ex.StackTrace.ToString)
End Try
End Sub
Private Sub Task2()
Try
While Not mReset.WaitOne(60000)
Try
'Perform some operation per minute
Catch ex As Exception
WriteMessage(ex.Message)
WriteMessage(ex.StackTrace.ToString)
End Try
End While
Catch ex As Exception
WriteMessage(ex.Message)
WriteMessage(ex.StackTrace.ToString)
End Try
End Sub