Browse DevX
Sign up for e-mail newsletters from DevX


Displaying Real-Time Stock Information Using Multithreading : Page 4

Learn to use multithreading to build applications whose UI remains active even while performing time-consuming or resource-intensive background tasks.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Displaying Multiple Stock Prices
You've seen how to call a Web service asynchronously without bogging down the UI of the application; however you can enhance the application by making it display information about more than one stock at a time.

In the same form, add a second set of controls (ChartFX, ComboBox, and a Button) along with a label, Pause, and Stop buttons as shown in Figure 6.

Figure 6. Enhanced Multi-Stock Form: The figure shows the new controls you need to add to the default form to chart two stocks simultaneously.
This enhanced example displays two charts simultaneously, and also displays the status of the thread that displays the second chart.

Add a second global variable t2:

Dim t1, t2 As Thread

The sample project uses a Timer control (located in the Toolbox) to display the status of the second thread. Drag the timer onto the form and set the timer's Interval property to 500, which causes the timer's Tick event to fire every half-second (500 milliseconds). Code in the Tick event handler below updates the thread's status in the label control named lblThreadStatus:

Private Sub Timer1_Tick( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Timer1.Tick lblThreadStatus.Text = "Thread state: " & _ t2.ThreadState.ToString End Sub

Use the same chart initialization code for the second chart control as you used for the first:

Private Sub Chart2_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Chart2.Load '---show the time on the x-axis every 5 point--- Chart2.AxisX.Step = 5 '---use 5 pixels to separate between each point--- Chart2.AxisX.PixPerUnit = 5 '---make chart scrollable--- Chart2.Scrollable = True '---Open and close the communication channel--- Chart2.OpenData(COD.Values, 1, COD.Unknown) Chart2.CloseData(COD.Values) End Sub

When you click the Get Stock Quote button for the second chart, the code spins off yet another thread—and also enables the Timer control so the form displays the thread status:

Private Sub btnGetStockQuote2_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnGetStockQuote2.Click Dim sq As New StockQuote sq.StockSymbol = cmbStocks2.SelectedItem sq.ChartControl = Chart2 t2 = New Thread(AddressOf sq.InvokeWebService) t2.Start() '---enable the Pause and Stop buttons btnPauseContinue.Enabled = True btnStop.Enabled = True '---Activate the Timer control Timer1.Enabled = True End Sub

Press F5 to test the two-chart version (see Figure 7). Select a stock for each chart, and you'll see the two charts displaying simultaneously.

Figure 7. Enhanced Two-Chart Application: The enhanced version displays two charts simultaneously.
When the second thread is running, notice that its status alternates between Running and WaitSleepJoin. This is because a thread is either in execution (Running) or sleeping (WaitSleepJoin). When the thread is paused, its state is WaitSleepJoin, Suspended. When the thread is aborted, its state first changes to AbortRequested and then to Stopped.

To pause the thread, first check the status of the running thread and then use the Suspend() method. After pausing a thread, you can resume it using the Resume() method.

Private Sub btnPauseContinue_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnPauseContinue.Click ' if thread is sleeping or running then suspend it If t2.ThreadState = ThreadState.WaitSleepJoin _ Or t2.ThreadState = ThreadState.Running Then t2.Suspend() btnPauseContinue.Text = "Continue" Else ' resume the thread t2.Resume() btnPauseContinue.Text = "Pause" End If End Sub

To stop a thread, use the Abort() method:

Private Sub btnStop_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnStop.Click Try If Not t2.ThreadState = ThreadState.Stopped Then btnPauseContinue.Enabled = False btnStop.Enabled = False t2.Abort() End If Catch ex As Exception MsgBox(ex.ToString) End Try End Sub

As you can see by running the sample project, you can use multithreading to build applications that remain responsive even while performing background tasks. While the example in this article uses Web services, the same principles apply to other types of background tasks. For example, you could adapt this application to read data from external devices such as a thermometer or blood pressure monitoring device.

Wei-Meng Lee is a Microsoft MVP and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies. He is an established developer and trainer specializing in .NET and wireless technologies. Wei-Meng speaks regularly at international conferences and has authored and coauthored numerous books on .NET, XML, and wireless technologies. He writes extensively on topics ranging from .NET to Mac OS X. He is also the author of the .NET Compact Framework Pocket Guide, ASP.NET 2.0: A Developer's Notebook (both from O'Reilly Media, Inc.), and Programming Sudoku (Apress). Here is Wei-Meng's blog.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date