. NET about synchronous, asynchronous and socket

Source: Internet
Author: User
Tags reset semaphore socket thread
Asynchronous

Take the asynchronous method in socket communication as an example:

public static ManualResetEvent Connectdone = new ManualResetEvent (false);

public static void Connectcallback (IAsyncResult ar)

{

Socket sclient = (socket) ar. asyncstate;

Sclient.endconnect (AR);

Console.WriteLine ("Socket connected to {0}", sClient.RemoteEndPoint.ToString ());

Connectdone.set ();

}

public static void Main (string[] arg)

{

Try

{

Iphostentry iphost = dns.resolve ("127.0.0.1");

IPAddress ipaddr = iphost.addresslist[0];

IPEndPoint endPoint = new IPEndPoint (ipaddr, 11000);

Socket sclient = new Socket (AddressFamily.InterNetwork,

SocketType.Stream, PROTOCOLTYPE.TCP);

Client.beginconnect (EndPoint, New AsyncCallback (Connectcallback), sclient);

for (int i = 0; I <5; i++)

Console.WriteLine ("Do Some the other Work.");

byte[] Bytedata = Encoding.ASCII.GetBytes ("Some Data.");

Connectdone.waitone ();

Sclient.beginsend (bytedata, 0, bytedata.length, 0,

New AsyncCallback (Sendcallback), sclient);

.........

}

(Note: ManualResetEvent allows threads to communicate with each other by signaling.) Typically, this communication involves a task that a thread must complete before other threads do so.

ManualResetEvent is like a semaphore that can use its signals to inform other threads. It has several important methods: Reset (), Set (), WaitOne (). When the object is initialized, the the user can specify its default state (signal/no signal), after initialization, the object will remain unchanged until its reset () or set () method is invoked, and the Reset () method sets it to no signal state, set () method to set it to a signaled state. The WaitOne () method suspends the current thread until the ManualResetEvent object is in a signaled state, at which point the thread is activated. )

In this case, the main thread calls Connectdone.waitone (), and the main thread blocks until the connection operation (that is, Connectcallback) completes, because after the connection operation completes, the Connectdone.set () is executed to signal the semaphore, Because the Manualresetevent.waitone () method is invoked and the main thread in the waiting state receives the signal, it then executes down and completes the work behind it.

Synchronous and asynchronous:

Simply put, synchronization means that the program executes a method, and when the method returns, it continues to go down,

Asynchronous: That is, the program calls a method immediately after the return, "macro", the main thread and method threads in parallel execution.

For this example, the asynchronous method BeginConnect of the socket is invoked, followed by the code following the statement in the main thread, namely:

for (int i = 0; I <5; i++)

Console.WriteLine ("Do Some the other Work.");

byte[] Bytedata = Encoding.ASCII.GetBytes ("Some Data.");

If the synchronization method is invoked, then the output "Socket connected to ..." is bound to be in "do Some the other Work." Before, because the main thread must wait for the synchronization method to return, but in the case of asynchrony, it would be possible to be in the 5 line "do Some the other Work." The output of the "Socket connected to ..." occurs at some point in time (the actual situation also relies on the operating system's thread schedule).

As for the Sclient.beginsend (...) method is called Connectdone.waitone () because the former relies on the completion of the connection operation (i.e. Connectcallback), it must be synchronized.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.