如果回调方法超过指定的Timer时间段会发生什么?

时间:2011-03-01 14:52:31

标签: vb.net windows-services

我有以下代码。如果上传方法需要超过一分钟才能完成,会发生什么?计时器是否在一分钟结束后立即启动对Upload方法的另一次调用,或者它是否等待方法完成执行?我将此实现为Windows服务。

Protected Overrides Sub OnStart(ByVal args() As String)    
  Dim tmr As Timer = New Timer(New TimerCallback(AddressOf Upload), Nothing, 1000, **60000**)

  While Not tmr Is Nothing
  End While
End Sub

Public Sub Upload(ByVal o As Object)
  Dim sr As StreamReader
  ..........
  ..........
End Sub

1 个答案:

答案 0 :(得分:1)

虽然您的某些代码令人困惑(While循环的内容是什么?),但我可以说是,Timer将从Thread启动另一个ThreadPool

您可以使用MonitorReaderWriterLockSlimlock来控制重新入侵。你需要一个对象锁定,其他东西与你的需求相关联(即指定的整数告诉Monitor尝试X毫秒,其中0表示我们想要立即锁定):

VB.NET:

Private ReadOnly LockerObject As Object = New Object()

If (Monitor.TryEnter(LockerObject, 0)) Then
    Try
        'do your processing
    Catch

    Finally
        'always release the lock
        Monitor.Exit(LockerObject)
    End Try
End If

C#:

private readonly object LockerObject = new object();

if (Monitor.TryEnter(LockerObject, 0))
{
    try
    {
        //do your processing
    }
    catch
    {
    }
    finally
    {
        //always release the lock
        Monitor.Exit(LockerObject);
    }
}
else
{
    //do something else here if needs be.
}
编辑:哎呀,这是VB.NET!让我转换我的代码......