A preliminary talk on C # multithreading, asynchronous programming and concurrent servers

Source: Internet
Author: User

Multi-threading and asynchronous programming can be achieved to avoid calling thread asynchronous blocking, but the two are still a bit different.

the similarities and differences between multi-threading and asynchronous Programming :

1. Threads are the basic unit of CPU scheduling resources and allocations, essentially a piece of code that executes concurrently in a process.

2. Thread programming thinking in line with normal people's thinking habits, threads in the process is still sequential execution, so it is easier to program, but the shortcomings are obvious, multi-threaded use will cause the context switch between multiple threads to bring the system costs, and shared variables will also cause a deadlock problem.

3. Because asynchronous operations do not require additional thread burdens and are handled in a callback manner, the processing function can eliminate the possibility of deadlocks by eliminating the need for shared variables (even if it is not completely unused, at least by reducing the number of shared variables). Of course, asynchronous operations are not flawless. Writing asynchronous operations is a high degree of complexity, the program mainly using callback methods to handle, and ordinary people's way of thinking, and difficult to debug.

Scope of application

After understanding the pros and cons of threading and asynchronous operations, we can explore the logical use of a thread and async. I think that when I am required to perform I/O operations, it is more appropriate to use asynchronous operations than to use thread + synchronous I/O operations. I/O operations include not only direct files, read and write to the network, but also database operations, Web Service, HttpRequest, and cross-process calls such as. NET Remoting.

The scope of the thread is the kind that requires long CPU operations, such as long-time graphics processing and algorithm execution. But often because of the simple and consistent use of threading programming, many friends tend to use threads to perform long-time I/O operations. This is harmless when there are only a few concurrent operations, which is not appropriate if you need to handle a large number of concurrent operations.

Second, multi-threaded programming

Just this time in the network programming, here in conjunction with multi-threaded and network programming, to meet the multi-client request service side. The Accept () method of the Socket class waits until there is a client connection request. Socket network programming can be referenced in C # Network programming socket programming.

There are special asynchronous network programming methods in C #, which can be used to refer to several socket server model comparisons.

Multithreaded implementation of a concurrent server example:

static Socket client;
static void Main (string[] args)
{
IPEndPoint Ipep = new IPEndPoint (Ipaddress.any, 9060); Creates a IPEndPoint object that accepts a client address of any port 9050
Socket Server = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); Tcp
Server. Bind (IPEP); Binding
Server. Listen (20); Listening
Console.WriteLine ("Listening ...");

The following code is blocked and can be executed with a new thread, but may be problematic
while (true)
{
Client = server. Accept (); Receive client requests

Open a new thread to send data
Thread recvthread = new Thread (senddata);
Recvthread. IsBackground = true; Background thread
Start the message service thread
Recvthread. Start ();
You can also open other threads, such as receiving data threads
}
}

static private void SendData ()
{
if (client! = NULL)
{
Console.WriteLine ("Client" + client.) Remoteendpoint + "connect to Server");
String data = "Hello client";
byte[] msg = System.Text.Encoding.ASCII.GetBytes (data); Converts a string to a byte array
Client. Send (msg); Data is occurring to the client
Console.WriteLine ("Occurrence data:" + data);
Client. Close ();
}
}

Three, asynchronous programming

There are three types of programming methods based on Async:

    • Asynchronous Programming Mode (APM), where asynchronous operations require the Begin and End methods (for example, BeginWrite and EndWrite of asynchronous write operations). This mode is no longer recommended for new development work.
    • The event-based Asynchronous Pattern (EAP) requires a method with an async suffix, and one or more events, event handlers, delegate types, and EventArg-derived types that are introduced in the. NET Framework version 2.0. This mode is no longer recommended for new development work.
    • A task-based Asynchronous Pattern (TAP) that uses a method to represent the start and finish of an asynchronous operation. The. NET Framework 4 introduces TAP and is the recommended method for asynchronous programming in the. NET Framework.

Task asynchronously, there are three ways to create the task:

    • Task.Factory.StartNew, more commonly used.

    • Task.run, which is added in. NET 4.5.

    • Task.fromresult, if the result is calculated, you can use this method to create the task.

The following is an example of implementing a concurrent server with Task.Factory.StartNew Asynchronous Programming:

static Socket client;
static void Main (string[] args)
{
IPEndPoint Ipep = new IPEndPoint (Ipaddress.any, 9060); Creates a IPEndPoint object that accepts a client address of any port 9050
Socket Server = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); Tcp
Server. Bind (IPEP); Binding
Server. Listen (20); Listening
Console.WriteLine ("Listening ...");

The following code block, can be placed on the sub-thread execution, but there may be problems, you can see the last side of the analysis
while (true)
{
Client = server. Accept ();
Create and start a task
Task.Factory.StartNew (() =
{
SendData (); A method with no return value
});
}
}

static private void SendData ()
{
if (client! = NULL)
{
Console.WriteLine ("Client" + client.) Remoteendpoint + "connect to Server");
String data = "Hello client";
byte[] msg = System.Text.Encoding.ASCII.GetBytes (data); Converts a string to a byte array
Client. Send (msg); Data is occurring to the client
Console.WriteLine ("Occurrence data:" + data);
Client. Close ();
}
}

Asynchronous programming using async and Await

static Socket client;
static Socket server;
static void Main (string[] args)
{
IPEndPoint Ipep = new IPEndPoint (Ipaddress.any, 9060); Creates a IPEndPoint object that accepts a client address of any port 9050
Server = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Tcp
Server. Bind (IPEP); Binding
Server. Listen (20); Listening
Console.WriteLine ("Listening ...");

Accept ();
}
static async void Accept ()
{
await Acceptasync ();
}
Static async Task Acceptasync ()//Asynchronous Accept Request
{
while (true)
{
Client = server. Accept (); Receive client requests
await SendData ();
}
}
Static async Task SendData ()//asynchronous occurrence of data
{
if (client! = NULL)
{
Console.WriteLine ("Client" + client.) Remoteendpoint + "connect to Server");
String data = "Hello client";
byte[] msg = System.Text.Encoding.ASCII.GetBytes (data); Converts a string to a byte array
Client. Send (msg); Data is occurring to the client
Add an Async method
Await Task.delay (1000);
Console.WriteLine ("Occurrence data:" + data);
Client. Close ();
}
}

Because the Main () function cannot be set to Async mode, an accept function is added, using await to perform an asynchronous operation Acceptasync (), waiting for the client's request to be accepted. Asynchronously executes the asynchronous SendData () in the asynchronous Operation Acceptasync () to send the data asynchronously.

a problem : In the above three programs, using multithreading and Task.Factory.StartNew implementation of the service side of the two programs, if the following two code as a sub-thread or asynchronous function execution, it would have been blocked function client = Server. Accept (), but did not wait for the client to connect, directly execute the past?? Is it because the accept () relationship is in both static function and multi-threading???? (Because this is not a problem in non-static functions), asynchronous functions executed with async and Await execute normally.

while (true)
{
Client = server. Accept (); Receive client requests

Open a new thread to send data
Thread recvthread = new Thread (senddata);
Recvthread. IsBackground = true; Background thread
Start the message service thread
Recvthread. Start ();
You can also open other threads, such as receiving data threads
}

while (true)
{
Client = server. Accept ();
Create and start a task
Task.Factory.StartNew (() =
{
SendData (); A method with no return value
});
}

A preliminary talk on C # multithreading, asynchronous programming and concurrent servers

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.