473,769 Members | 1,730 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thread Sync Queue Problem

I have an interesting problem with a sort of producer-consumer system
for error logging. Consider the following code:

<code>
SyncLock _eventList.Sync Root

Dim item As ExceptionLogEnt ry

' If there are items, get the top one
If _eventList.Coun t > 0 Then

' Get the item from the queue
item = CType(_eventLis t.Dequeue, _
ExceptionLogEnt ry)

' If we got an item to log, log it
If Not item Is Nothing Then

WriteToLog(Buil dExceptionRepor t(item))

End If

End If

End SyncLock
</code>

This method is running as a new thread, created thus:

<code>
_thread = New Thread(AddressO f StartWatching)
_thread.Start()
</code>

FACTS:
1) The _thread is System.Threadin g.Thread, the _eventList is
System.Collecti ons.Queue, both are member variables of the class.

2) The class this code appears in could have more than one instances
(hence using threading).

3) I'm using .NET 1.1.

4) The _eventList object is referenced by the producer class (not
listed here), where Enqueue is called inside a SyncLock block.

MY PROBLEM:
Thing is, it seems that "_eventList.cou nt > 0" returns true, and still
is just before the dequeue call, but after the dequeue call it goes to
0, and "item" is NOTHING!!

I have no idea why this could be. Can anyone help!?!

Cheers,

<Shipcreak />

Full class follows:

Imports System.Text
Imports System.Threadin g

Public MustInherit Class LoggerBase

Private _name As String
Private _eventList As Queue
Private _thread As Thread
Private _stopRequested As Boolean

Public Sub New(ByVal pName As String)
_name = pName
End Sub

Public Sub AssignEventList (ByVal eventList As Queue)
If Not _eventList Is Nothing Then
SyncLock _eventList
_eventList = eventList
End SyncLock
Else
_eventList = eventList
End If
End Sub

Public Sub Start()

_stopRequested = False

_thread = New Thread(AddressO f StartWatching)

If Not _name Is Nothing AndAlso _name.Length > 0 Then
_thread.Name = _name
Else
_thread.Name = "Event Logging Thread"
End If

_thread.Start()

End Sub

Public Sub RequestStop()
_stopRequested = True
End Sub

Private Sub StartWatching()

While Not _stopRequested

' Lock the list
SyncLock _eventList.Sync Root

Dim item As ExceptionLogEnt ry

' If there are items, get the top one
If _eventList.Coun t > 0 Then

' Get the item from the queue
item = CType(_eventLis t.Dequeue, ExceptionLogEnt ry)

' If we got an item to log, log it
If Not item Is Nothing Then

WriteToLog(Buil dExceptionRepor t(item))

End If

End If

End SyncLock
' Wait for 1 sec to allow other threads to take their turn
Thread.CurrentT hread.Sleep(100 )

End While

End Sub

Private Function BuildExceptionR eport( _
ByVal ex As ExceptionLogEnt ry) As String

Dim ret As New StringBuilder
Dim e As ExceptionLogEnt ry = ex

If Not e Is Nothing Then

ret.AppendForma t("OS: {0}" & vbCrLf, ex.OSInfo)
ret.AppendForma t("Processor usage: {0}" & vbCrLf, _
ex.ProcessorUsa ge)
ret.AppendForma t("Working Set: {0}" & vbCrLf, _
ex.WorkingSet)
ret.AppendForma t("Free Memory: {0}" & vbCrLf, _
ex.FreeMemory)
ret.AppendForma t("OS UserName: {0}" & vbCrLf, _
ex.OSUserName)
ret.AppendForma t("Machine Name: {0}" & vbCrLf, _
ex.MachineName)
'ret.AppendForm at("Total HDD: {0}" & vbCrLf, _
ex.HDDTotal)
'ret.AppendForm at("Free HDD: {0}" & vbCrLf, _
ex.FreeHDD)
ret.AppendForma t("Occurred At: {0}" & vbCrLf, _
ex.Occurred)
ret.Append("Exc eption details:" & vbCrLf)

AppendException Details(ex.Caus ingException, ret)

WriteToLog(ret. ToString)

Else

WriteToLog("No exception data provided")

End If

End Function

Private Sub AppendException Details(ByVal ex As Exception, _
ByVal report As StringBuilder)

Dim e As Exception = e

Do While Not e Is Nothing

report.AppendFo rmat(" Message: {0}" & vbCrLf, _
e.Message)
report.AppendFo rmat(" Source: {0}" & vbCrLf, _
e.Source)
report.AppendFo rmat(" Method: {0}" & vbCrLf, _
e.TargetSite.Na me)
report.AppendFo rmat(" Help Link: {0}" & vbCrLf, _
e.HelpLink)
report.AppendFo rmat(" Stack Trace: {0}" & vbCrLf, _
e.StackTrace)
report.Append("------------------" & vbCrLf)

e = e.InnerExceptio n

Loop

End Sub

Protected MustOverride Sub WriteToLog(ByVa l item As String)
Protected MustOverride Sub WriteToLog(ByVa l item As String, _
ByVal type As EventLogEntryTy pe)

End Class

May 8 '06 #1
2 2132

sh*******@gmail .com wrote:
I have an interesting problem with a sort of producer-consumer system
for error logging. Consider the following code:

<code>
SyncLock _eventList.Sync Root

Dim item As ExceptionLogEnt ry

' If there are items, get the top one
If _eventList.Coun t > 0 Then

' Get the item from the queue
item = CType(_eventLis t.Dequeue, _
ExceptionLogEnt ry)

' If we got an item to log, log it
If Not item Is Nothing Then

WriteToLog(Buil dExceptionRepor t(item))

End If

End If

End SyncLock
</code>
In my not-particularly-expert opinion, this looks OK.

[snip] 4) The _eventList object is referenced by the producer class (not
listed here), where Enqueue is called inside a SyncLock block.

MY PROBLEM:
Thing is, it seems that "_eventList.cou nt > 0" returns true, and still
is just before the dequeue call, but after the dequeue call it goes to
0, and "item" is NOTHING!!

I have no idea why this could be. Can anyone help!?!


I think you're going to have to have a look at the enqueueing code, and
if you can't find the problem, post some of it. The key point which you
may need reminding of (from the docs, my emphasis):
Queue.Enqueue Method

Adds an object to the end of the Queue.

Public Overridable Sub Enqueue( _
ByVal obj As Object _
)

Parameters
obj
The object to add to the Queue. ****The value can be a null reference
(Nothing in Visual Basic). ****

My example code:

Sub Main()
Dim q As New Queue

q.Enqueue("appl e")
q.Enqueue("bana na")
q.Enqueue(Nothi ng)
q.Enqueue("pear ")

Dim o As Object
Do While q.Count > 0
o = q.Dequeue
' everything implements ToString, right?
Console.WriteLi ne(o.ToString)
' OOPS
Loop

Console.ReadLin e()
End Sub

--
Larry Lard
Replies to group please

May 8 '06 #2
Yeah, you're right. I worked out what it was yesterday afternoon
eventually.

I was adding the result of a call to a factory class method to the
queue, but the factory was returning Nothing.

Put null in, get null out. Simple.

Thanks for the reply, one's never guaranteed one in here, so many
people with so many problems an' all that. :-)

<Shipcreak />

May 10 '06 #3

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

Similar topics

44
2376
by: Charles Law | last post by:
Hi guys. I'm back on the threading gig again. It's the age-old question about waiting for something to happen without wasting time doing it. Take two threads: the main thread and a worker thread. The worker thread is reading the serial port, waiting for something to happen (a service request). When it does it raises an event. Of course, the event is executed on the worker thread. The idea is that when the event is raised, the handler...
13
2068
by: Paul | last post by:
Hi, How do I wait until a thread is finished his job then continue to the original thread? public void main(string args) { Thread t = new Thread(new ThreadStart(DoWork)); t.Start();
5
2221
by: taylorjonl | last post by:
I am completely baffled. I am writting a daemon application for my work to save me some time. The application works fine at my home but won't work right here at work. Basically I have a MainForm what has a Start/Stop button that starts and stops the processing thread. private void StartButton_Click(object sender, System.EventArgs e) { if( bStopSignal ) { // disable controls that aren't valid when running
5
3430
by: jzlondon | last post by:
Hi, I have a question that I wonder if someone might be able to help me with... I have an application which handles real-time financial data from a third party source. The data comes in via events which are fired on an arbitrary thread, and I then take the data, generate update commands for a SQL Server database, and add them to a queue using a lock on a sync object to ensure thread safety when writing to the queue.
5
1378
by: Svein Seldal | last post by:
Hi, I have a C-application that calls a Python function main(). This function will loop forever and not return until the entire application is about to terminate. In a parallel C-thread, some data must be regularly delivered to the running python application. My initial plan was to call a py function deliver() from this thread, however I constantly run into troubles. I keep getting a "Fatal Python error: ceval: tstate mix-up" error...
8
12098
by: mtsweep | last post by:
Hi, I started a background thread to preform some time intensive tasks for a GUI frontend. This background thread uses a C++ object which requires a windows message loop so I started one in it by calling Application.Run(). Now I can see that messages from the C++ libraries are being processed. But how do I send my own messages to this thread from the GUI frontend? I tried to use delegates/events/etc but it ends up either spawning a...
7
7260
by: Boki | last post by:
Multi-thread read/write to a single file. I have two processing threads, thread A and thread B; and I called my queue as Q. Thread A will feed data into Q by user input, the timing is random. Thread B will read data from Q to process; this processing will communicate with a website. I think the best Q architecture is ring buffer as large as possible.
5
1793
by: P.J.M. Beker | last post by:
Hi there, I'm currently writing a program in which I use the FileMonitor to monitor a folder in which I store downloaded images. I know that I can't add much coding in the filemonitor's event in risk of losing some new entries, so I've deceided to create an update thread. This thread is created when the program's start and should (for various reason) run not in sync with the Filemonitor. The Filemonitor event creates an entry in a...
8
2984
by: Brad Walton | last post by:
Hello. First post, but been doing a bit of reading here. I am working on a project in Java, but decided to switch over to C# after seeing some of the additional features I can get from C#. One of the big changes I want to make is event-driven code (rather than the linear flow I had in Java). I have spent a week or so searching Google, talking to a couple of programming friends, and just chewing on it in my brain. I think I have an ok handle...
0
9589
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10211
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10045
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9994
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7408
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3958
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.