调度程序代码中的问题

时间:2010-11-22 14:02:32

标签: .net scheduler

以下代码-scheduler.vb-使用ASP.NET模拟Windows服务以运行计划作业。更多信息:http://beckelman.net/post/2008/09/20/Simulate-a-Windows-Service-Using-ASPNET-to-Run-Scheduled-Jobs.aspx

当我尝试在我的global.asax中运行该类时,我得到以下错误(在RunScheduledTasks上突出显示):“表达式不会产生值”,为什么?感谢。

的global.asax

 Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    Scheduler.Run("test", 1, RunScheduledTasks)
End Sub


 Public Sub RunScheduledTasks()
 'Do stuff here
 end Sub

scheduler.vb

 Public Class Scheduler
Private Class CacheItem
    Public Name As String
    Public Callback As Callback
    Public Cache As Cache
    Public LastRun As DateTime
End Class

Public Delegate Sub Callback()

Private Shared _numberOfMinutes As Integer = 1

Public Shared Sub Run(ByVal name As String, ByVal minutes As Integer, ByVal callbackMethod As Callback)
    _numberOfMinutes = minutes

    Dim cache As New CacheItem()
    cache.Name = name
    cache.Callback = callbackMethod
    cache.Cache = HttpRuntime.Cache
    cache.LastRun = DateTime.Now
    AddCacheObject(cache)
End Sub

Private Shared Sub AddCacheObject(ByVal cache_1 As CacheItem)
    If cache_1.Cache(cache_1.Name) Is Nothing Then
        cache_1.Cache.Add(cache_1.Name, cache_1, Nothing, DateTime.Now.AddMinutes(_numberOfMinutes), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, _
         AddressOf CacheCallback)
    End If
End Sub

Private Shared Sub CacheCallback(ByVal key As String, ByVal value As Object, ByVal reason As CacheItemRemovedReason)
    Dim obj_cache As CacheItem = DirectCast(value, CacheItem)
    If obj_cache.LastRun < DateTime.Now Then
        If obj_cache.Callback IsNot Nothing Then
            obj_cache.Callback.Invoke()
        End If
        obj_cache.LastRun = DateTime.Now
    End If
    AddCacheObject(obj_cache)
End Sub
End Class

1 个答案:

答案 0 :(得分:0)

查看您提供的链接,看起来这可能是从C#到VB的错误转换。 C#代码会自动创建一个Callback委托,其RunScheduledTasks作为目标传递给Scheduler.Run

我怀疑你的VB.Net代码正在考虑这一行:

Scheduler.Run("test", 1, RunScheduledTasks)

并期望RunScheduledTasks成为返回Callback委托的函数。不幸的是,我不知道VB.Net,所以我猜这里。如果您添加AddressOf运算符(link),它可能会起作用,如下所示:

Scheduler.Run("test", 1, AddressOf RunScheduledTasks)