473,396 Members | 2,087 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

SyncLock Required?

Jay
Given the following code I am wondering if SyncLock is required. Because I
am using system.timer is there already this type of lock behaviour in place?
I need to assure that I'm only selecting one distinct record at a time per
thread...

Public Class Form1

Private MessageArray() As MessageHandler
Private MH As MessageHandler

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

MH = New MessageHandler

Dim i As Integer
Dim iTo As Integer = 4 '4 threads
Dim iFrom As Integer = 1

ReDim MessageArray(iTo - iFrom)
Dim Msg As MessageHandler
For i = iFrom To iTo
Msg = New MessageHandler()
MessageArray(i - iFrom) = Msg
'pass parameters to the new thread
Msg.i = i
Msg.MainForm = Me
Dim ts As ThreadStart
ts = New ThreadStart(AddressOf Msg.ProcessingOutboundThread)
Dim wrkThread As Thread
wrkThread = New Thread(ts)
Msg.CurrentThread = wrkThread
wrkThread.SetApartmentState(ApartmentState.STA)
wrkThread.Name = i.ToString() 'for easier tracing
wrkThread.Start()
Next
'end start
End Sub

End Class

Class MessageHandler

Public MainForm As Form1
Public i As Integer
Public CurrentThread As Thread
Public iThreadId As Integer
Public cnString As String =
"server=servername;database=dbname;uid=username;pw d=password"
Private WithEvents Timer1 As System.Timers.Timer

Private Sub Timer1_Elapsed(ByVal sender As Object, ByVal e As
System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed

iThreadId = Thread.CurrentThread.GetHashCode()

Dim cn As SqlConnection
cn = New SqlConnection(cnString)
Dim cmd As SqlCommand
Dim dtr As SqlDataReader

Try
Try
cmd = New SqlCommand("select top 1 * from queue_table where
time_to_send=1", cn)
cn.Open()
dtr = cmd.ExecuteReader()
If dtr.HasRows() = True Then
dtr.Read()
Dim varE As String = dtr("employeetosendto")
Dim varM As String = dtr("employeemessageaddress")
dtr.Close()
cmd = New SqlCommand("update queue_table set
time_to_send=0 where employee='" & varE & "'", cn)
cmd.ExecuteNonQuery()
Call_Send_Message_Sub_Here 'call another sub pass employeemessageadress as
param
cmd = New SqlCommand("update queue_table set
sentmessage=1 where employee='" & varE & "'", cn)
cmd.ExecuteNonQuery()
end if
Catch ex As Exception
msgbox(ex.Message.ToString())
Finally
If cn.State = ConnectionState.Open Then cn.Close()
End Try
End If
Catch ex As Exception
msgbox(ex.Message.ToString())
Finally
If cn.State = ConnectionState.Open Then cn.Close()
End Try
End Sub

Public Sub ProcessingOutboundThread()
Dim iThreadId As Integer
iThreadId = Thread.CurrentThread.GetHashCode()

Timer1 = New System.Timers.Timer
Timer1.Interval = 5000 ' 5 seconds
Timer1.Start()

Application.Run()
End Sub
End Class

I'd appreciate any feedback on how I can make this a more threadsafe app or
more stable app. Thanks a lot.

Jay

Dec 1 '06 #1
1 1684

Jay wrote:
Given the following code I am wondering if SyncLock is required. Because I
am using system.timer is there already this type of lock behaviour in place?
I need to assure that I'm only selecting one distinct record at a time per
thread...

Public Class Form1

Private MessageArray() As MessageHandler
Private MH As MessageHandler

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

MH = New MessageHandler

Dim i As Integer
Dim iTo As Integer = 4 '4 threads
Dim iFrom As Integer = 1

ReDim MessageArray(iTo - iFrom)
Dim Msg As MessageHandler
For i = iFrom To iTo
Msg = New MessageHandler()
MessageArray(i - iFrom) = Msg
'pass parameters to the new thread
Msg.i = i
Msg.MainForm = Me
Dim ts As ThreadStart
ts = New ThreadStart(AddressOf Msg.ProcessingOutboundThread)
Dim wrkThread As Thread
wrkThread = New Thread(ts)
Msg.CurrentThread = wrkThread
wrkThread.SetApartmentState(ApartmentState.STA)
wrkThread.Name = i.ToString() 'for easier tracing
wrkThread.Start()
Next
'end start
End Sub

End Class

Class MessageHandler

Public MainForm As Form1
Public i As Integer
Public CurrentThread As Thread
Public iThreadId As Integer
Public cnString As String =
"server=servername;database=dbname;uid=username;pw d=password"
Private WithEvents Timer1 As System.Timers.Timer

Private Sub Timer1_Elapsed(ByVal sender As Object, ByVal e As
System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed

iThreadId = Thread.CurrentThread.GetHashCode()

Dim cn As SqlConnection
cn = New SqlConnection(cnString)
Dim cmd As SqlCommand
Dim dtr As SqlDataReader

Try
Try
cmd = New SqlCommand("select top 1 * from queue_table where
time_to_send=1", cn)
cn.Open()
dtr = cmd.ExecuteReader()
If dtr.HasRows() = True Then
dtr.Read()
Dim varE As String = dtr("employeetosendto")
Dim varM As String = dtr("employeemessageaddress")
dtr.Close()
cmd = New SqlCommand("update queue_table set
time_to_send=0 where employee='" & varE & "'", cn)
cmd.ExecuteNonQuery()
Call_Send_Message_Sub_Here 'call another sub pass employeemessageadress as
param
cmd = New SqlCommand("update queue_table set
sentmessage=1 where employee='" & varE & "'", cn)
cmd.ExecuteNonQuery()
end if
Catch ex As Exception
msgbox(ex.Message.ToString())
Finally
If cn.State = ConnectionState.Open Then cn.Close()
End Try
End If
Catch ex As Exception
msgbox(ex.Message.ToString())
Finally
If cn.State = ConnectionState.Open Then cn.Close()
End Try
End Sub

Public Sub ProcessingOutboundThread()
Dim iThreadId As Integer
iThreadId = Thread.CurrentThread.GetHashCode()

Timer1 = New System.Timers.Timer
Timer1.Interval = 5000 ' 5 seconds
Timer1.Start()

Application.Run()
End Sub
End Class

I'd appreciate any feedback on how I can make this a more threadsafe app or
more stable app. Thanks a lot.

Jay
Jay,

The Elapsed event on System.Timers.Timer will run on a thread from the
ThreadPool if SynchronizingObject is null. When SynchronizingObject is
set to a Form or Control then the Timer will automatically marshal the
Elapsed event onto the thread hosting that Form or Control. In your
case the Elapsed event is running on another thread because you aren't
setting the SynchronizingObject property.

The thread running ProcessingOutboundThread isn't doing much. In fact,
the only thing it's doing is getting a Timer started. After that it
just blocks on Application.Run consuming system resources. You can
just as easily get the Timer started on the main UI thread inside the
Form_Load event.

Better yet, set the SynchronizingObject property to Form1 and the
Elapsed event will always run on the main UI thread. That will
absolutely guarentee that the queries will be executed one at a time.
And of course, since there wouldn't be more than one thread in play the
issue of thread-safety is moot.

Brian

Dec 1 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: fred | last post by:
If I have multiple threads running a Sub as below then a number of threads can be held up at the SyncLock. When it becomes free which thread goes first. Is it just by chance which thread goes first...
10
by: Bob Day | last post by:
Using vs 2003, vb.net sql msde.. Consider the following code snippets. See **** for questions. All are shared and accessed by multiple threads simultaneiously. ' Instantiate per for this...
3
by: Bob Day | last post by:
Ok, I have done a lot of reading(of the newsgroup answers, help files and MSDN articles) of synclock. I understand what you are saying in the newsgroup, and it is very helpful. It does, however,...
4
by: fred | last post by:
I use a Synclock in a secondary thread and also stop the thread using the abort method. If the abort occurs while the thread is in the Synclock will the SyncLock always be released before the...
1
by: Joel Denton | last post by:
I have a question about when synclock is necessary. Most of the examples I've seen have suggested synclocking on a static/shared object for synchronizing access to class data. What I'm not clear...
4
by: Jeff Stewart | last post by:
Specifically, I don't understand the parameter that Synclock accepts. How is a reference type a lockable entity? What -is- a reference type? Is it a number? Is it a value at a specific memory...
7
by: SD | last post by:
I have a public object that I only want one thread to access at a time. However the access to this object is not limited to one procedure. Will SyncLock work in this case? If not what options do I...
1
by: fred | last post by:
I have a VB application that is using MS Access as its database. To avoid connection delays the application creates one connection to the database at start-up and maintains that single connection...
2
by: HONOREDANCESTOR | last post by:
I have a buffer that needs to be locked sometimes, because 2 processes update it. So I made the buffer into a class and whenever there is code that affects it, I sandwich the code between ...
2
by: cj | last post by:
I take it a mutex is like a synclock but visible outside the program?
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.