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

MultiThreading c# message exchanger, PulseAll problem

344 100+
Hello,
I'm trying to do an ASP.NET message-exchanger (littel messenger).
I chose a long scenario; using JavaScript not to reload the page by requesting another page "CommPage.aspx" that implements C# methods, Implementing the famous reader/writer problem using Monitors. As this:
1) on page load a receive request occurs to "CommPage.aspx", on "CommPage.aspx" a reader thread start.
2) on button click a send request to "CommPage.aspx" occurs, then a writer thread start.
3) Reader thread:
Expand|Select|Wrap|Line Numbers
  1.         Monitor.Enter(_myRoom);
  2.         Monitor.Wait(_myRoom);
  3.         Monitor.Exit(_myRoom);
Then read a property that contain the message (string). Then send a receive request again (Circulation).
4) Writer thread:
First set a property message
Expand|Select|Wrap|Line Numbers
  1.         Monitor.Enter(this);
  2.  
  3.         /// rarely happen when more than one request to write arrive to
  4.         /// server at the same time.
  5.         if (_writer)
  6.             Monitor.Wait(this);
  7.  
  8.         _writer = true;
  9.  
  10.         _writer = false;
  11.         Monitor.PulseAll(this);
  12.         Monitor.Exit(this);
  13.         try { Thread.CurrentThread.Abort(); }   catch { }
I view more than one page in browser to test.
The problem is when a send request occurs only the first loaded page has a receive response. with another send request the second loaded page has get receive response. Then the third ..... .

It seems to me like Monitor.PulseAll acts like Monitor.Pulse.
Please What I'm wrong about?

Any help, Thanks.
Jun 14 '09 #1
3 2985
Bassem
344 100+
I'm sorry maybe I didn't declare my problem well.
I'm trying to create chatting rooms where more than one instant client can entre. And for each client can entre more than one chatting room simultaneously.
It is a simple design two web pages (Default.aspx, CommPage.aspx) and two classes (Groups, ChattingRoom).
1) Default.aspx : my main page I do some DHTML (changes on client-side) so I use JavaScript to do whatever I want.
On page load send a receive-request to CommPage.aspx with group name
Expand|Select|Wrap|Line Numbers
  1.  function page_load()
  2. {
  3.     /// on load request for new data
  4.     receiveData("g1");
  5. }
  6.  function receiveData(group)
  7. {
  8.     if(null==xmlHttpReceiver)
  9.     {
  10.         alert("Your browser does not support AJAX!");
  11.         return;
  12.     }
  13.  
  14.     var url="CommPage.aspx";
  15.     url=url+"?way=receive"+"&group="+group;
  16.  
  17.     xmlHttpReceiver.onreadystatechange=receiverStateChanged;
  18.     xmlHttpReceiver.open("GET",url,true);
  19.     xmlHttpReceiver.send(null);
  20. }
  21.  function receiverStateChanged() 
  22.     if (xmlHttpReceiver.readyState==4)
  23.     { 
  24.         document.getElementById("Text2").value = xmlHttpReceiver.responseText + "\r\n";
  25.  
  26.         /// after receiving request to receive again;
  27.         /// circulation
  28.         receiveData("g1");
  29.     }
On button click send a send-request to CommPage.aspx with group name and user name and message (all are strings).
Expand|Select|Wrap|Line Numbers
  1.  function Button2_onclick() {
  2.  
  3.     var mess = document.getElementById('Text1').value;
  4.     document.getElementById("Text1").value="";
  5.     sendData("g1","u1",mess);
  6. }
  7.  function sendData(group, user, message)
  8. {
  9.     if (message.length==0)
  10.       { 
  11.           return;
  12.       }
  13.     if (xmlHttpSender==null)
  14.       {
  15.           alert ("Your browser does not support AJAX!");
  16.           return;
  17.       } 
  18.     var url="CommPage.aspx";
  19.     url=url+"?way=send"+"&message="+message+"&user="+user+"&group="+group;
  20.  
  21.     xmlHttpSender.onreadystatechange=senderStateChanged;
  22.     xmlHttpSender.open("GET",url,true); // POST 
  23.     xmlHttpSender.send(null);
  24. }
2) CommPage.aspx: executes c# methods.
on Page_Load verify the request either send or receive request
Expand|Select|Wrap|Line Numbers
  1.  public partial class Default2 : System.Web.UI.Page
  2. {
  3.     Groups _groups = Groups.Instance;
  4.     ChatRoom _myRoom;
  5.  
  6.     protected void Page_Load(object sender, EventArgs e)
  7.     {
  8.         Response.Expires = -1;
  9.  
  10.         if ("receive" == Request.QueryString["way"])
  11.             ReceiveRequested();
  12.         else
  13.             SendRequested();
  14.     }
  15.  
  16.     private void SendRequested()
  17.     {
  18.         _myRoom = _groups.MyRoom(Request.QueryString["group"]);
  19.         string groupName = Request.QueryString["group"];
  20.         string userName = Request.QueryString["user"];
  21.         string message = Request.QueryString["message"];
  22.  
  23.  
  24.         //try then catch null reference and redirect to custom error page, so that'll happend only
  25.         // if this page is requested directly and no parameters are set.
  26.  
  27.         _myRoom.NewMessageContent = userName + " says :" + message + Environment.NewLine;
  28.         Thread writer = new Thread(new ThreadStart(Write));
  29.         writer.Start();
  30.     }
  31.  
  32.     private void ReceiveRequested()
  33.     {
  34.         _myRoom = _groups.MyRoom(Request.QueryString["group"]);
  35.  
  36.         Read();
  37.         Response.Write(_myRoom.AllConversation);
  38.     }
  39.  
  40.     public void Read()
  41.     {
  42.         Monitor.Enter(_myRoom);
  43.         Monitor.Wait(_myRoom);
  44.         Monitor.Exit(_myRoom);
  45.     }
  46.  
  47.     public void Write()
  48.     {
  49.         Monitor.Enter(_myRoom);
  50.  
  51.         /// rarely happend when more than one request to write arrive to
  52.         /// server at the same time.
  53.         if (_myRoom._writer)
  54.             Monitor.Wait(_myRoom);
  55.  
  56.         _myRoom._writer = true;
  57.  
  58.         _myRoom._allText += _myRoom.NewMessageContent;
  59.  
  60.         _myRoom._writer = false;
  61.         Monitor.PulseAll(_myRoom);
  62.         Monitor.Exit(_myRoom);
  63.         try { Thread.CurrentThread.Abort(); }
  64.         catch { }
  65.     }
  66. }
Readers only wait until a writer pulse all of them.
3) Group class : is shared among all classes that reference it (singleton)
Expand|Select|Wrap|Line Numbers
  1.  public class Groups
  2. {
  3.     static readonly Groups _groups = new Groups();
  4.     List<ChatRoom> _rooms = new List<ChatRoom>(); 
  5.     bool editor;
  6.  
  7.     private Groups()
  8.     {
  9.  
  10.     }
  11.  
  12.     public ChatRoom EnterChat(string roomName, string userName)
  13.     {
  14.         Monitor.Enter(this);
  15.  
  16.         if (editor)
  17.             Monitor.Wait(this);
  18.         editor = true;
  19.  
  20.         foreach (ChatRoom room in _rooms)
  21.         {
  22.             if (room.Name == roomName)
  23.             {
  24.                 editor = false;
  25.                 Monitor.PulseAll(this);
  26.                 Monitor.Exit(this);
  27.                 return room;            
  28.             }
  29.         }
  30.  
  31.         ChatRoom newRoom = new ChatRoom(roomName);
  32.         _rooms.Add(newRoom);
  33.  
  34.         editor = false;
  35.         Monitor.PulseAll(this);
  36.         Monitor.Exit(this);
  37.         return newRoom;                 
  38.     }
  39.  
  40.     public ChatRoom MyRoom(string roomName)
  41.     {
  42.         foreach (ChatRoom room in _rooms)
  43.             if (room.Name == roomName)
  44.                 return room;
  45.         return null;
  46.     }
  47.  
  48.     public static Groups Instance
  49.     {
  50.         get { return _groups; }
  51.     }
  52. }
4) ChattRoom class : contains only string to save the conversation.
Expand|Select|Wrap|Line Numbers
  1.  public class ChatRoom
  2. {
  3.     readonly string _name;
  4.  
  5.     public string _allText = string.Empty;
  6.     public string _newMessage;
  7.  
  8.     public bool _writer;
  9.  
  10.     public ChatRoom(string name)
  11.     {
  12.         _name = name;
  13.         }
  14.  
  15.     public string NewMessageContent
  16.     {
  17.         set { _newMessage = value; }
  18.         get { return _newMessage; }
  19.     }
  20.  
  21.     public string Name
  22.     {
  23.         get { return _name; }
  24.     }
  25.  
  26.     public string AllConversation
  27.     {
  28.         get { return _allText; }
  29.     }
Everything works fine but when a writer PulseAll waiting threads (Readers) only one thread notified and response.

Please any help! Any idea!
Thanks in advanced.
Jun 15 '09 #2
Frinavale
9,735 Expert Mod 8TB
Hmm I'm not sure how much help I'm going to be because I haven't done much threading stuff before (mainly just used it in school...and in load capacity testing).

I looked up the PulseAll method. It says the following:
The thread that currently owns the lock on the specified object invokes this method to signal all threads waiting to acquire the lock on the object. After the signal is sent, the waiting threads are moved to the ready queue. When the thread that invoked PulseAll releases the lock, the next thread in the ready queue acquires the lock.
It seems to me that the PulseAll method is doing exactly what it is supposed to: a thread locks the Object, does something and gets a response from the Object, then the next thread is able to gain a lock. This would mean that only 1 thread would get the response.

Maybe the PulseAll method isn't the method you should be using.
Consider researching the other methods available to you to find one that does suit your needs.

-Frinny
Jun 16 '09 #3
Bassem
344 100+
Thanks Frinny, I think you did help me much.
How come I forgot that using Monitor and lock, allow only one thread to acquire the lock on a particular object until it releases it and threads in waitsleepjoin should be pulsed before. But only one thread working in the critical part of code at a time.

I tried to use Monitor.Suspend() and Monitor.Resume() but they are decade cuz of some problems they have.

I converted to ManualResetEvent works but I'm trying to set a condition that threads should WaitOne() on it.

Your words enlightened me thanks again and again.
Bassem
Jun 17 '09 #4

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

Similar topics

11
by: Mark Yudkin | last post by:
The documentation is unclear (at least to me) on the permissibility of accessing DB2 (8.1.5) concurrently on and from Windows 2000 / XP / 2003, with separate transactions scope, from separate...
16
by: Robert Zurer | last post by:
Can anyone suggest the best book or part of a book on this subject. I'm looking for an in-depth treatment with examples in C# TIA Robert Zurer robert@zurer.com
6
by: Michael C | last post by:
Hello Can someone please tell me what I'm doing wrong? I'm writing an application that should be using callbacks to perform asynchronous calls to the Win32 API. Problem is it never reaches my...
5
by: sarge | last post by:
I would like to know how to perform simple multithreading. I had created a simple form to test out if I was multithreading properly, but got buggy results. Sometime the whole thig would lock up...
16
by: who be dat? | last post by:
Consider the following code which enables multithreading in an ASP.Net application I'm writing: Code in global.asx Application_start subroutine, Threadnotify is declared Globally as a new thread...
2
by: Rich | last post by:
Hello, I have set up a multithreading routine in a Test VB.net proj, and it appears to be working OK in debug mode and I am not using synchronization. Multithreading is a new thing for me, and...
2
by: shonend | last post by:
**** sorry about the length of the message. If you can't read the whole thing and still willing to help, read the last 2 paragraphs where the main problem is described. The introduction story is...
2
by: Multithreading problem in vb.net | last post by:
Greetings, I am new to multithreading and I am trying to implement it in my app. This application is distributed application which needs to refresh every say 5 secs to show some activities in...
2
by: Pradnya Patil | last post by:
hi , I am trying to draw ' html div-tag ' on the screen which will resemble a rectangle through vb.net code. I want it to be drawn faster...so I introduced multithreading using Threadpool. I...
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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...

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.