How to make calls across threads?

S

Siegfried Heintze

The following code below is single threaded. When I click the start button,
it hogs the message pump so none of the UI works. How can I convert this to
make it multi-threaded so I can continue to be user friendly and service my
message pump while the timer loop does something time consuming? I will have
problems if I execute the "lblTimeDisplay.Text = newval" in a thread that is
different from the one that created it, won't I?

Thanks,
Siegfried

Imports System
Imports System.ComponentModel
Imports System.Drawing
Imports System.Windows.Forms
Imports Microsoft.VisualBasic.DateAndTime
Public Class Form1
Inherits Form
Public WithEvents btnStart As Button
Private WithEvents mText as TimerState = New TimerState
Public lblTimerDisplay as Label
Public Sub New()
btnStart = New Button()
btnStart.Size = New Size(80, 20)
btnStart.Location = New Point(10, 10)
btnStart.Text = "start timer"
Me.Controls.Add(btnStart)

lblTimerDisplay = new Label()
lblTimerDisplay.Location = New Point(10,40)
lblTimerDisplay.Text = "Timer Display"
lblTimerDisplay.Size = New Size(80,30)
Me.Controls.Add(lblTimerDisplay)
End Sub 'New
Private Sub btnStart_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles btnStart.Click
mText.TimerTask(9.84)
End Sub
<STAThread()> _
Public Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
Private Sub mText_UpdateTime(ByVal Jump as Double) Handles
mText.UpdateTime
lblTimerDisplay.Text = Microsoft.VisualBasic.Format(Jump, "##0.00")
Application.DoEvents()
End Sub
End Class
Class TimerState
Public Event UpdateTime(ByVal Jump As Double)
Public Sub TimerTask(ByVal Duration As Double)
Dim Start as Double
Dim Second as Double
Dim SoFar as Double
Start = Microsoft.VisualBasic.DateAndTime.Timer
SoFar = Start
Do While Microsoft.VisualBasic.DateAndTime.Timer < Start + Duration
If Microsoft.VisualBasic.DateAndTime.Timer - SoFar >= 0.1 Then
SoFar = SoFar + 0.1
RaiseEvent UpdateTime(Microsoft.VisualBasic.DateAndTime.Timer-
Start)
End If
Loop
End Sub
End Class
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top