C # asynchronous socket programming

Source: Internet
Author: User

1. Use the loop mode:

//.....
Manualresetevent alldone = new manualresetevent (false); // semaphore
Listener. Listen (100 );
While (true)
{
Alldone. Reset ();
Listener. beginaccept (New asynccallback (acceptcallback), listener );
Alldone. waitone ();
}
Void acceptcallback (iasyncresult result)
{
Alldone. Set ();
//......
}
Sometimes I find it hard to understand the manualresetevent class. I can summarize the information on the Internet and my understanding as follows:

Manualresetevent mainly deals with the blocking relationship between the main thread and the sub-thread,
Reset (): allows other threads to be blocked, that is, blocking threads containing the waitone () method. That is to say, other waiting sub-threads are allowed to block the main thread containing the waitone method.

Set (): This method sends a signal to the operating system, so that the waiting touch thread is converted from the blocking state to the running, that is, the thread containing the waitone method is no longer blocked. S

Waitone (): blocks the current thread until it receives the Signal Set ()

2. Use the callback method:

You do not need to use a signal. You can directly access the acceptcallback and then use the beginaccept command, for example:

Listener. Listen (100 );
Listener. beginaccept (New asynccallback (acceptcallback), listener );

Void acceptcallback (iasyncresult result)
{
Socket skserver = (socket) result; // The linster socket responsible for listening
Socket skclient = listener. endaccept (result)
Listener. beginaccept (New asynccallback (acceptcallback), skserver );
}

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.