Jump to content

semaphores (waitHandle) vs. events

- - - - -

  • Please log in to reply
No replies to this topic

#1
eran50

eran50

    Newbie

  • Members
  • Pip
  • 1 posts
hello , i am new to the world of programing so please keep an open mind becuase some of my defenitions might be misleading (like semaphores ) as i reffer to the manualResetEvent class wich works as one( to my understanding )

so any ways what im trying to understand regards Events ,

this is part of a socket chat program that im writing ,i will not go into the communicaition part at this time, ive tryied 2 approches to make asyncrouns communicaition , the first( wich workes ) , is by using ManualResetEvent instances for each client to block the current thread that hes running on

on the server side for sending and receving as shown in the example ( ill show just one since they are quite similar // Send )
.
.
currentClient.sendDone.Reset();

currentClient.netstream.BeginWrite(currentClient.SendBuffer, 0, currentClient.SendBuffer.Length, new AsyncCallback(SendCallBack), currentClient);

currentClient.sendDone.WaitOne();
.
.

private void SendCallBack(IAsyncResult ar)
{
Client c = (Client)ar.AsyncState;

c.netstream.EndWrite(ar);

c.sendDone.Set();
}

// the sendDone (Semaphore) is set to non-signaled , the callback method is called to being sending ,
sendDone tells the current Thread to pause execution until sendDone is signaled by the set method to resume thread ops. , after the network stream via socket ends writing to a remote end point .

NOW IVE TRIED A DIFFRENT APPROCH for my understanding of the .NET surroundings and for efficiency and the clarity of my code , the second approch is to use a self specified Events For Send and Recevie

THE QUESTION : is using an event as so interchangble with my first approch ,
as to my understanding the when an event is dispatched it receives the Systems
divided attention (resources) , thus no need for semphores ..?
on the same subject if i want from my delegated method to write to a control such
as a textbox i woldent have to use INVOKE ?... becuase the method was dispathced by the main thread ?


public delegate void SendDelegate(object sender, EventArgs e); // decler delegate
.
.
public event SendDelegate OnSend; // declere event
.
.
OnSend += new SendDelegate(SendData); // combine a delegate method
.
.
.
/* some where in the code dispatching the event*/

OnSend(currentClient,myArgs) ;


// the method
public void SendData(object sender, EventArgs e)
{
Client c = (Client)sender;

c.netstream.BeginWrite(c.SendBuffer, 0, c.SendBuffer.Length, new AsyncCallback(EventSendCallBack),c.netstream);
}

private void EventSendCallBack(IAsyncResult ar)
{
NetworkStream ns = (NetworkStream)ar.AsyncState;

ns.EndWrite(ar);
}

thank you , i hope for a quick replay :).




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users