473,320 Members | 1,862 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,320 software developers and data experts.

C# Queue

I am very new to C# and am writing a program that needs a Form with some controls and 2 other separate threads that run continuously and talk to each other.

this example has worked really well for me in a similar application in Python in the past and I understand it well, so I would like to bring it over to C# if possible. I am stuck at how to share the q object between the two classes. Can anyone point me in the right direction?
Expand|Select|Wrap|Line Numbers
  1. #very over simplified and abridged Python example
  2. q = Queue.Queue(100)
  3.  
  4. class c1:
  5.     def __init__(self, q):
  6.         while 1:
  7.             do stuff and add result to queue...
  8.             q.put("data")
  9.  
  10. class c2:
  11.     def __init__(self, q):
  12.         while 1:
  13.             q.get()
  14.             do other stuff after taking from queue...
  15.  
  16. threada = c1(q)
  17. threadb = c2(q)
  18. threada.start()
  19. threadb.start()
  20.  
Jan 21 '12 #1
2 3702
The simplest way I can see how to do it is as follows.

Expand|Select|Wrap|Line Numbers
  1. static class globalvar {
  2.     q = Queue.Queue(100)
  3. }
To reference it use
Expand|Select|Wrap|Line Numbers
  1. globalvar.q
And to tidy it up a little, put your subroutines (while, if, class, etc.) within '{' and '}'.

Hope that helps.
Jan 22 '12 #2
Joseph Martell
198 Expert 128KB
In a very simple system a global queue object is fine, but I think it is generally advisable to avoid a global state.

If you are looking to move your logic to C# you may want to take a look at a publish/subscription pattern or an observer pattern.

It is easiest to avoid race conditions or other thread problems if someone owns the queue and controls access to adding or removing items. For this example, I am going to give the queue to the processing thread. The following code example is not tested so there may be problems, but it should give you enough info to get started:

Expand|Select|Wrap|Line Numbers
  1.     public class Processor
  2.     {
  3.         private System.Collections.Queue _processQueue = new System.Collections.Queue();
  4.         public void AddProcessItem(object o)
  5.         {
  6.             if (o != null)
  7.             {
  8.                 lock (_processQueue)
  9.                 {
  10.                     _processQueue.Enqueue(o);
  11.                 }
  12.             }
  13.         }
  14.  
  15.         public void ProcessQueue()
  16.         {
  17.             Object processObject = null;
  18.             while (true)
  19.             {
  20.                 if (_processQueue.Count > 0)
  21.                 {
  22.                     lock (_processQueue)
  23.                     {
  24.                         processObject = _processQueue.Dequeue();
  25.                     }
  26.  
  27.                     //do processing
  28.                 }
  29.             }
  30.         }
  31.     }
  32.  
  33.  
By moving the queue inside a class you are limiting access to the queue object and therefore limiting potential threading problems.

To add items to the queue, another class is defined that takes a reference to a processor object. This reference is the "subscription" part of the pattern mentioned above. The reference creates a link between the two objects so information can be passed to the processing thread:
Expand|Select|Wrap|Line Numbers
  1.     public class Adder
  2.     {
  3.         private Processor _p = null;
  4.         public Adder(Processor p)
  5.         {
  6.             if (p == null)
  7.             {
  8.                 throw new System.ArgumentNullException();
  9.             }
  10.             _p = p;
  11.         }
  12.  
  13.         public void DoStuff()
  14.         {
  15.             while (true)
  16.             {
  17.                 //do a bunch of stuff...add item to process queue
  18.                 _p.AddProcessItem(new object());
  19.             }
  20.         }
  21.     }
  22.  
The key here is that one object owns the queue and controls how the queue is accessed. This prevents race conditions and any other threading problems that may come up otherwise. The thread that adds items to the queue gets a reference to the object that owns the queue. All adding to the queue is taken care of by the owning object, again avoiding threading problems.

This model does allow you to add some flexibility to your system if you choose. For example: You can have multiple processing objects and multiple adding objects. The adding objects can be dynamically assigned a queue so you can change who processes items dynamically.

This code example does leave out some fairly large details like how the processing object monitors the queue. It really should not be in a constant loop like shown above. You can do something as simple as schedule a timer to periodically trigger processing of the queue or add more complex logic to trigger the processing method whenever an item is added to the queue. Other experts that have a lot of experience with this pattern may be able to offer better advice on how to overcome that particular challenge.

Hope this helps.
Jan 23 '12 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: phil | last post by:
And sorry I got ticked, frustrating week >And I could help more, being fairly experienced with >threading issues and race conditions and such, but >as I tried to indicate in the first place,...
9
by: Brian Henry | last post by:
If i inherite a queue class into my class, and do an override of the enqueue member, how would i then go about actually doing an enqueue of an item? I am a little confused on this one... does over...
4
by: alisaee | last post by:
plz check what i have made wrong what is requierd her is to creat class queue and class stack and run the push,pop operation . #include<iostream.h> #include<conio.h> #include<stdio.h> class...
3
by: Kceiw | last post by:
Dear all, When I use #include "queue.h", I can't link it. The error message follows: Linking... G:\Projects\Datastructure\Queue\Debug\main.o(.text+0x136): In function `main':...
5
Rooro
by: Rooro | last post by:
Hello everyone i'm working on : " Familiar childhood games such as hide and Go Seek and Tag involve determining the player who is to be "It". One method has the players stand in a circle...
2
by: lavender | last post by:
When define a maxQueue is 10, means it able to store 10 items in circular queue,but when I key in the 10 items, it show "Queue Full" in items number 10. Where is the wrong in my code? Why it cannot...
3
by: jrpfinch | last post by:
I have a script which is based on the following code. Unfortunately, it only works on Python 2.3 and not 2.5 because there is no esema or fsema attribute in the 2.5 Queue. I am hunting through...
4
by: j_depp_99 | last post by:
Thanks to those guys who helped me out yesterday. I have one more problem; my print function for the queue program doesnt work and goes into an endless loop. Also I am unable to calculate the...
2
by: ecestd | last post by:
how do you implement a copy constructor for this pointer-based ADT queue #include <cassert // for assert #include <new // for bad_alloc using namespace std; //private:{Queue::Queue(const...
0
by: ecestd | last post by:
I did implement the copy constructor but still have a problem with it. It is not working. What could be wrong? #include "QueueP.h" #include <cassert // for assert #include <new // for...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.