423,822 Members | 1,356 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 423,822 IT Pros & Developers. It's quick & easy.

How to make calls across threads?

P: n/a
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
Oct 22 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"Siegfried Heintze" <si*******@heintze.comwrote in
news:OU**************@TK2MSFTNGP03.phx.gbl:
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?
You need to marshal the call back to the UI thread:

http://www.codeproject.com/useritems...ead.asp?df=100
&forumid=387684&exp=0&select=1903029
Oct 22 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.