Use. NET multithread technology display real time stock information

Source: Internet
Author: User
Tags format sleep thread thread class tostring web services window visual studio
Multithreading | display

The content of this article is to learn how to build an application using multithreaded technology, so that the user interface (UI) is still active while the application is performing time and resource-intensive background transactions.

Multithreading Technology (multithreading) is one of the most powerful concepts in programming. With multithreading, you can split complex transactions into multiple threads that are executed independently of each other. A good multithreaded application is naturally synchronized, similar to a Web service invocation. By default, a Web service invocation belongs to a blocking (blocking) call-that is, the caller (caller) code stops executing until the Web service returns the result. However, because Web service calls are usually slow, it can cause client performance to degrade unless you take special steps to make the call asynchronous.

This article explains how to build a chart application, from which you can see how to invoke the Web service asynchronously without impacting the client UI. The sample code uses the Chart FX component to display stock information using graphics. Of course, readers can also use. NET write a free chart class library.

  Set up a Web service

The sample code needs access to the hypothetical stock quote Web service. We set up a Web service in Visual Studio. NET 2003 and named it "Stockws." This Web service consists of a Web method called GetPrice () that accepts only one stock encoding parameter:

Public Function GetPrice (ByVal-as String) as single
return Rnd () * 100
End Function

Regardless of what the requested stock is, the GetPrice () method generates a random price. Its only goal is to simulate a real web service that returns a specific stock price.
Although this article uses a molded Web service to demonstrate, you can easily replace the Web service to display real stock information.

   displaying graphics using the Chart FX component

After you have established the Web service project above, add a Windows Application project to the solution browser (called the stock Quote, the ticker quote). Add a reference to the project to the Web service you established earlier. The solution browser should now be shown in Figure 1.


Figure 1: The project in Solution Explorer-the figure shows the STOCKWS Web service project and

   Windows Forms project Stock Quote

To build the sample project for this article, you must download and install the Chart FX component 30-day trial from http://chartfx.com/. After you install the drawing component, you can see it in the visual Studio. NET 2003 Tool box (shown in Figure 2).


Figure 2: The Chart Component in the tool box-you will need to download and install the Chart FX component 30-day trial from the website.

In the default Form1 for this Windows application, populate the form with some of the following controls, as shown in Figure 3:

· Chart
· ComboBox
· Button


Figure 3:stock Quote main form-The figure shows the form style after adding the appropriate control.

The Chart (Drawing) component offers many options for customizing your behavior and appearance. You can format this Chart component by using the wizard (located at the bottom of the property form, as shown in Figure 4).


Figure 4:chart The Format Wizard for the component-the wizard provides a number of formatting options for the Chart component.

The easiest way to use the example is to copy and paste some of the following chart properties into the code snippet generated by the Windows Forms Designer:

Chart1
Me.Chart1.AxisX.Staggered = True
Me.Chart1.Axi Sx.step = Ten
Me.Chart1.AxisY.Step = ten
Me.Chart1.BackObject = GradientBackground1
Me.Chart1.DataStyle = SoftwareFX.ChartFX.DataStyle.ReadXValues
Me.Chart1.DesignTimeData = _
"C:\Program files\chartfx for. NET 6.2\ Wizard\xyzero.txt "
Me.Chart1.Gallery = SoftwareFX.ChartFX.Gallery.Lines
Me.Chart1.InsideColor = System.Drawing.Color.Transparent
Me.Chart1.LineWidth = 3
Me.Chart1.Location = New System.Drawing.Point (40, 16)
Me.Chart1.MarkerShape =softwarefx.chartfx.markershape.none
Me.Chart1.Name = "Chart1"
Me.Chart1.NSeries = 1
Me.Chart1.NValues =
Me.Chart1.Palette = "Highcontrast.highcontrast"
Me.Chart1.PointLabels = True
Me.Chart1.Size = new System.Drawing.Size (656, 216)
Me.Chart1.TabIndex =
Me.Chart1.Titles.AddRange (New _
SoftwareFX.ChartFX.TitleDockable () {TitleDockable1})

Also, add some of the following data items to the combo box control: "MSFT", "SUN", "YHOO", and "GE". You can do this in the Form_Load event:

Me.cmbStocks1.Items.AddRange (New String () {"MSFT", "SUN", "YHOO", "GE"})

  Activate graphics

Next, import the following namespace (at the top of the code window):

Imports Softwarefx.chartfx
Imports System.Threading

Defines the global variable T1 for a thread:

Dim T1 as Thread

In the Chart1_load event, initialize the Chart component:

Private Sub chart1_load (ByVal sender as _
System.Object, ByVal e as System.EventArgs) Handles Chart1.load
' X-axis shows time at every 5 points
Chart1.AxisX.Step = 5
' with 5 pixel intervals between each point
Chart1.AxisX.PixPerUnit = 5
' Make the chart scroll
Chart1.scrollable = True
' Open and close the communication pipeline
Chart1.opendata (COD. Values, 1, COD. Unknown)
Chart1.closedata (COD. Values)
End Sub

Adds a class called StockQuote to the current form. The StockQuote class invokes the preceding Web service and updates the chart with the returned stock price.

Public Class StockQuote
' Number of graphs in the component
Const num_series = 1

Private lastpoint as Integer = 0
Dim StockPrice as Single

Private Pstocksymbol as String
Private pstockseries as Integer = 0
Private Pchartcontrol as Chart

WriteOnly Property StockSymbol ()
Set (ByVal Value)
Pstocksymbol = Value
End Set
End Property

WriteOnly Property Chartcontrol ()
Set (ByVal Value)
Pchartcontrol = Value
End Set
End Property

Public Sub Invokewebservice ()
Dim ws as New Stockws.service1

For i as Integer = 0 to 10000
StockPrice = Ws.getprice (Pstocksymbol)
Pchartcontrol.invoke (New _
MyDelegate (AddressOf updatechart), New Object () {})
' Wait 1 seconds before continuing
Thread.Sleep (1000)
Next
End Sub

Public Delegate Sub MyDelegate ()
Public Sub Updatechart ()
Pchartcontrol.opendata (COD. Values, Num_series, COD. Unknown)
Pchartcontrol.value (pstockseries, lastpoint) = StockPrice
' Show the time on the X axis
PChartControl.AxisX.Label (lastpoint) = DateTime.Now.ToShortTimeString
Lastpoint + 1
Pchartcontrol.closedata (COD. Values)
' Move the scroll bar to the right
PChartControl.AxisX.ScrollPosition = PChartControl.AxisX.ScrollSize
End Sub

End Class

You pass the StockSymbol attribute to the desired stock encoding to the StockQuote class and use the Chartcontrol property to set the chart update. The Invokewebservice () method periodically invokes the above Web service in the loop (set to 10,000 in the example). Since this class executes in a separate thread, you must be very careful to ensure that you do not automatically update a Windows control because the Windows control is not thread safe (thread-safe). Instead, you must use the delegate and invoke the Invoke () method on the control that you want to update. The code calls the Web service once per second, which is set by the Thread.Sleep (1000) statement.

To start the thread update the chart with the latest stock information, add the following code to the Click event for the "Get Stock quote" button:

Private Sub Btngetstockquote1_click (ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles Btngetstockquote1.click
Dim sq as New StockQuote
Sq. StockSymbol = Cmbstocks1.selecteditem
Sq. Chartcontrol = Chart1
T1 = New Thread (AddressOf sq. Invokewebservice)
T1. Start ()
End Sub

The primary reason for packaging code that invokes the Web service as a class is that the thread class constructor can only accept one ThreadStart delegate (a delegate of the method that initiates the thread), and there is no overloaded Thread.Start () method that can accept multiple parameter values. Therefore, the only way to pass multiple parameters to a thread is to package the associated code of the call into a class, and then you can pass arguments through the arguments of the class.

Press F5 to test this code, select a stock and click the "Get Stock quote" button. You can now move the window (that is, the UI is not locked by repeated Web service calls), and you can see that the chart has been updated with the latest stock information (Figure 5).


Figure 5: Testing the application-when you select a stock code and click on the "Get Stock Quote" button, the result of the recurring call to the Web service is displayed in the chart, but because the Web service is running on a background thread, calling it does not affect normal UI actions.

  Show the price of multiple stocks

You've seen how to invoke a Web service asynchronously without pausing the application's UI, but you can also enhance the application to display multiple messages at the same time.

In the same form, add another set of controls (Chartfx, combo boxes and buttons) and labels, pauses, stop buttons (shown in Figure 6).


Figure 6: Enhanced multi-stock form-this figure shows a new control you need to add to the default form to display two stock graphs at the same time.

This enhanced example displays two graphics, along with the state information for the thread that displays the second shape.

Add a second global variable T2:

Dim T1, T2 as Thread

The sample project uses a Timer control (timer, in the Toolbox) to display state information for the second thread. Drag the timer onto the form and set its Interval property to 500, which causes the timer's tick event to be called once every half second (500 milliseconds). The code in the Tick event handler updates the thread state information in the label control 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

The second chart also uses the same initialization code as the first chart:

Private Sub chart2_load (ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles Chart2.load
' Show time every 5 points on the X axis
Chart2.AxisX.Step = 5
' separated by 5 pixels between each point
Chart2.AxisX.PixPerUnit = 5
' Make the chart scroll
Chart2.scrollable = True
' Open and close the communication pipeline-
Chart2.opendata (COD. Values, 1, COD. Unknown)
Chart2.closedata (COD. Values)
End Sub

When you click the "Get Stock Quote" button on the second chart, the code creates a new thread--activating the timer so the form can display the status information of the thread:

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 ()

' Activate pause and stop button
btnpausecontinue.enabled = True
btnstop.enabled = True
' Activate the Timer control
timer1.enabled = True
End Sub

Press F5 to test the two charts (shown in Figure 7). Select a stock for each chart and you will see the two graphs synchronized.


Figure 7: The enhanced two-chart application-The enhanced version shows two charts at the same time.

When the second thread is running, you can notice that its state is alternating between running and waitsleepjoin. This is because a thread is either executing (Running) or sleeping (WaitSleepJoin). When the thread is paused, its state is WaitSleepJoin, suspended. When the thread is canceled, its state is first abortrequested, and then it becomes stopped.

If you want to suspend the thread, you need to first detect the state of the running threads, and then use the Suspend () method. After pausing a thread, you can continue to execute it using the Resume () method.

Private Sub Btnpausecontinue_click (ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles Btnpausecontinue.click
' Suspend it if the thread is asleep and running
If T2. ThreadState = Threadstate.waitsleepjoin _
Or T2. ThreadState = threadstate.running Then
T2. Suspend ()
Btnpausecontinue.text = "Continue"
Else
' Continue the thread
T2. Resume ()
Btnpausecontinue.text = "Pause"
End If
End Sub

The stop thread uses 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

By running the sample project, you will find that you have been able to use multithreaded technology to build your application so that the application remains responsive when performing background transactions. Although the example in this article uses Web services, the same principle can also be applied to other types of background transactions. For example, you can change the application to read data from an external device, such as a thermometer or sphygmomanometer monitoring device.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.