use timer in a vb.net dll
I need to wait for and event within a given period (30s) and then timeout if this time elapse. What do I need to do?
Am sending a command to a server from a dll, and i need to wait for response before sending another. I want to implement a timeout feature, that why i need to use a timer
I want to use a timer, but don't know how to use it in a DLL开发者_运维问答.
There are four timers in .NET - System.Windows.Forms.Timer
, System.Threading.Timer
and System.Timers.Timer
, and System.Windows.DispatcherTimer
.
You can use any of them from a class library just as well as from an executable, but you need to choose the most appropriate one to your situation - which isn't very clear.
If you expect to be running within a UI thread, you should use an appropriate UI-based timer; otherwise one of the others. The more information you can give, the more we'll be able to help.
This little piece of code illustrates why using a timer to represent an interval of time is generally a bad idea
Dim WithEvents myTimer As New Windows.Forms.Timer 'a timer
Dim stpw As New Stopwatch
Dim count As Long
Const intervalValue As Integer = 1000 'some number of ms. s/b > 10
Private Sub myTimer_Tick(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles myTimer.Tick
count += 1
Dim foo As Long = count * intervalValue 'the interval using tick firing every intervalValue ms.
Dim bar As Long = stpw.ElapsedMilliseconds 'the actual amount of time that has passed
Label1.Text = foo.ToString("n0")
Label2.Text = bar.ToString("n0")
Label3.Text = (bar - foo).ToString("n0") 'show error
End Sub
Private Sub Form1_Shown(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Shown
myTimer.Interval = intervalValue 'number of ms.
myTimer.Start()
stpw.Start()
End Sub
A better approach is to set the timer to some smaller value, say one second for your example, and see if the elapsed time is greater than the value you are looking for.
精彩评论