siha 0 Newbie Poster

Hi folks,

I have written client and server applications. The messages from client flow continuously but not periodically to the server. At the server side, an event fires and a procedure is called when a message arrives at the server. This procedure runs slowly. While it is running, it can be called due to new arrivals. This procedure must not be called before completing its job. In order to run the code efficiently I thought thread pooling is the best solution.

To test the thread pooling I have written the following code but there is a problem. Briefly, 6 threads are created in for loop and it is expected that each thread must start after that the previous one complete its job. The job is to wait for its index second(s), e.g. thread 3 must wait for 3 seconds. At the end, you'll see the output. It seems that threads don't follow each other sequentially. What is the problem? How can I solve it, or have you got any suggestion about the problem above? Each answer/solution will be highly appreciated.

Dim Freq, VelX, VelY As Single
Declare Function QueryPerformanceCounter Lib "Kernel32" (ByRef X As Long) As Short
Declare Function QueryPerformanceFrequency Lib "Kernel32" (ByRef X As Long) As Short

Dim Handlex As WaitHandle

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim k As Short
Handlex = New AutoResetEvent(False)

For k = 1 To 6
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf dalla), k)
Next

t.Text &= "OK" & vbNewLine
Handlex.WaitOne()
End Sub

Private Sub dalla(ByVal state As Object)
If Delay(state * 1000) = 1 Then
CType(Handlex, AutoResetEvent).Set()
End If
t.Text &= state & vbNewLine
End Sub

Function Delay(ByVal mseconds As Short) As Short
SyncLock Me
Dim start, cou1, fre, cou2 As Single
QueryPerformanceCounter(cou1)
QueryPerformanceFrequency(fre)
Do
Application.DoEvents()
QueryPerformanceCounter(cou2)
start = ((cou2 - cou1) / fre) * 1000
Loop Until start >= mseconds
If start >= mseconds Then
Delay = 1
t.Text &= Microsoft.VisualBasic.DateAndTime.Now.Second & "-"
End If
End SyncLock
End Function

Here is the output(second-sequence):
OK
31-1
33-2
36-3
41-5
47-6
51-4

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.