MSSql MySql Python javascript PHP java DotNet Ruby Hackme Takeawy Code Twitter Facebook

The house of developers, A website to classify and rank developers

 
 
 
 
Country Rank: 1
World Rank: 4
Profile Viewed: 51412
Points: 55012
30 Dec 2010

threading in .net


Creating Threads
To create threads lets work with an example
, Programming with Visual Basic.NET- Black Book. Open a new windows application and name it as Thread and add a class named count1 using the Projects->Add Class item. This class will count from 1 to a specified value in a data member named CountTo when you call the Count method. After the count has reached the value in CountTo, a FinishedCounting event will  occur. The code for the Count class looks like this:

 

Public Class Count1
Public CountTo as Integer
Public event FinishedCounting(By Val NumberOfMatches as Integer)
Sub Count()
Dim ind,tot as Integer
tot=0
For ind=1 to CountTo
tot+=1
Next ind
RaiseEvent FinishedCounting(tot)
'makes the FinishedCounting event to occur
End Sub
End Class


Let's use this class with a new thread.  Get back to the main form and create an object of this class, counter1, and a new thread, Thread1. The code looks like this:

 

Public Class Form1 Inherits System.Windows.Forms.Form
Dim counter1 as new Count1()
Dim Thread1 as New System.Threading.Thread(Address of counter.Count)


Drag a Button and two TextBoxes (TextBox1, TextBox2) onto the form. Enter a number in TextBox1. The reason for entering a number in textbox is to allow the code to read the value specified in TextBox1 and display that value in TextBox2, with threading. The code for that looks like this:

 

Public Class Form1 Inherits System.Windows.Forms.Form
Dim counter1 as new Count1()
Dim Thread1 as New System.Threading.Thread(Address of counter.Count)
Private Sub Button1_Click(ByVal sender as System.Object, ByVal e as System.EventArgs)_
Handles Button1.Click
TextBox2.Text=" "
counter1.CountTo=TextBox1.Text
AddHandler counter1.FinishedCounting,AddressOfFinishedCountingEventHandler
'adding handler to handle FinishedCounting Event
Thread1.Start()
'starting the thread
End Sub
Sub FinishedCountingEventHandler(ByVal Count as Integer)
'FinishedCountingEventHandler
TextBox2.Text=Count
End Sub


The result of the above code displays the value entered in TextBox1, in TextBox2 with the difference being the Thread counting the value from 1 to the value entered in TextBox1.

Facebook Share Delicious Share Digg Share Google Buzz Share My Space Share Reddit Share Stumbleupon Share Technorati Share Twitter Share

Comments

Please, login or register to add a comment.