Threads are a powerful abstraction for allowing
parallelized operations: graphical updates can happen while another
thread is performing computations, two threads can handle two
simultaneous network requests from a single process, and the list
goes on. Since threads are pretty simple to understand,
conceptually, but, practically, they are a cause for programmatic
headaches, I decided to write this program to describe how to make
use of threads.
To understand this code completely, you need to have some
basics on C# language. I used some form and controls that are easy
to understand. You can refer to the MS Visual Studio Documentation
to understand the System.Threading.Thread class and all its
properties and methods.
Using the code.
The project AutoChess.sln consists of three classes:
This program, when executed, shows the
previous grid. If one presses the (Start) button, those pieces start
to move in random fashion. The King moves in any direction and the
soldier moves in diagonals. Let's have a closer look at the code. We
declared four threads, one for each piece:
Dim t1, t2, t3, t4
Then we create our four threads:
t1 = New Thread(AddressOf
t2 = New Thread(AddressOf
t3 = New Thread(AddressOf
t4 = New Thread(AddressOf
Where MoveWhiteKing,MoveBlackKing,... are delegates that refer to
methods responsible for moving the pieces. And I decided also to
create an object for each piece used. Those are:
WK = New
WindowsApplication1.King(bs, WhiteKingPic, WhiteSoldierPic).
BK = New
WindowsApplication1.King(bs, BlackKingPic, BlackSoldierPic).
WS = New
WindowsApplication1.King(bs, WhiteSoldierPic, WhiteKingPic,
BS = New
WindowsApplication1.King(bs, BlackSoldierPic, BlackKingPic,
To start the four threads, the following code is put in
button1_Click(), which is the Start button:
Private Sub button1_Click(ByVal
sender As Object,
End Sub 'button1_Click.
To understand more how each thread works let's have a closer look
at the method referenced by the delegates. Let's take the
MoveWhiteKing() as an example:
Private Sub MoveWhiteKing().
End Sub 'MoveWhiteKing.
We use the synchronizeVariable object that is assigned in the
beginning of the program:
Public Shared synchronizeVariable
As [Object] = "locking