C #3.0 learning notes (12) process, thread and asynchronous programming

Source: Internet
Author: User

 

There is nothing to do when I leave home, so I will take this opportunity to summarize the asynchronous programming technology to share with you.

1. What is a process? What is thread?

Process: A process is a group of resources that constitute a running program. These resources include virtual address spaces, file handles, and carriers of other things required for program startup. When we start a program, the system is in the memory

A new Process is created ).

Thread: In the process, the system creates a kernel object called a thread, which reflects the actual execution of a program. Once the program is ready, the system starts to execute the first statement of the Main method in the system thread. Mo

Under normal conditions, a process only contains one thread, starting from program execution to program completion.

2. What is asynchronous programming (or multithreading )?

Before understanding what asynchronous programming is, let's take a look at what Synchronous Programming is. So far, all the programs we mentioned earlier have only one thread, and execute the statements from the first line of the program to the last line in sequence. This is called the same

Step programming. Asynchronous programming refers to the process of initiating multiple threads, which are theoretically executed at the same time. (In fact, it may not be executed at the same time)

The following describes two simple but very powerful multithreading technologies, asynchronous delegation and Timer:

Asynchronous delegation:

Asynchronous delegation has three standard modes:

1. wait until the completion (wait-until-done) mode: After an Asynchronous Method is initiated and some other processing is done, the original thread is interrupted and continues after the Asynchronous Method is completed.

2. Polling mode: the original thread regularly checks whether the initiated thread is complete. If not, you can continue to do other things.

3. Callback mode: the original thread is always executed without waiting or checking whether the initiated thread is complete. After the method is referenced in the initiated thread, the initiated thread calls the callback method. The callback method processes the Asynchronous Method before calling EndInvoke.

Structure.

The following figure shows the execution process of the three modes:

The following shows a complete example of the three modes:

1. Example of waiting till the end mode:

 

 

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using System. Threading;

 

Namespace thread1

{

Delegate long MyDel (int first, int second); // declare the delegate type

Class Program

{

Static long Sum (int x, int y) // declares the Asynchronous Method and specifies the method matching delegate.

{

Console. WriteLine ("Inside Sum ");

Thread. Sleep (100); // call the Sleep method of the Thread class to suspend it for 0.1 seconds.

Return x + y;

}

 

Static void Main (string [] args)

{

MyDel del = new MyDel (Sum); // create a delegate object and use the Sum method to initialize its call list

 

Console. WriteLine ("Before BeginInvoke ");

IAsyncResult iar = del. BeginInvoke (3, 5, null, null); // starts asynchronous calling. BeginInvoke returns a reference to an IAsyncResult interface.

Console. WriteLine ("After BeginInvoke ");

 

Console. WriteLine ("Doing stuff ");

 

Long result = del. EndInvoke (iar); // wait until the end and obtain the result. The IAsyncResult object must be referenced as a parameter.

Console. WriteLine ("Ater EndInvoke: {0}", result );

Console. ReadKey ();

}

}

} Program output result:

 

 

2. Example of Polling mode:

 

 

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using System. Threading;

 

Namespace thread2

{

Delegate long MyDel (int first, int second); // declare the delegate type.

Class Program

{

Static void Main (string [] args)

{

MyDel del = new MyDel (Sum); // create a delegate object.

 

IAsyncResult iar = del. BeginInvoke (3, 5, null, null); // initiates an asynchronous call. BeginInvoke returns a reference to an IAsyncResult interface.

Console. WriteLine ("After BeginInvoke ");

 

While (! Iar. IsCompleted) // call the IsCompleted attribute of the IAsyncResult interface to check whether the Asynchronous Method is complete.

{

Console. WriteLine ("Not Done ");

 

// Continue processing. Here, "processing" is only counted from 0 to 10000000.

For (long I = 0; I <10000000; I ++)

; // Empty statement.

}

Console. WriteLine ("Done ");

 

Long result = del. EndInvoke (iar); // call the delegate EndInvoke method to obtain the interface and clear it.

Console. WriteLine ("Result: {0}", result );

Console. ReadKey ();

 

}

 

Static long Sum (int x, int y) // declare a method match delegate.

{

Console. WriteLine ("Inside Sum ");

Thread. Sleep (500); // call the Sleep method of the Thread class to suspend it for 0.5 seconds.

Return x + y;

}

}

} Program output result:

 

 

3. Sample Code for Callback mode:

 

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using System. Threading;

Using System. Runtime. Remoting. Messaging;

 

Namespace thread3

{

Delegate long MyDel (int first, int second); // declare the delegate type.

 

Class Program

{

Static long Sum (int x, int y) // declare a method match delegate.

{

Console. WriteLine ("Inside Sum ");

Thread. Sleep (100); // call the Sleep method of the Thread class to suspend it for 0.1 seconds.

Return x + y;

}

 

Static void CallWhenDone (IAsyncResult iar) // declare the callback method.

{

Console. WriteLine ("Inside CallWhenDone ");

AsyncResult ar = (AsyncResult) iar; // converts an interface reference to a reference of an AsyncResult class object through reference conversion.

MyDel del = (MyDel) ar. AsyncDelegate; // call the AsyncDelegate attribute of the Class Object and convert it to the delegate type, so that we can call the delegate EndInvoke method.

Long result = del. EndInvoke (iar); // end the call, obtain the return value of the asynchronous method call, and release the resources used by the thread.

Console. WriteLine ("The result is {0}", result );

}

 

Static void Main (string [] args)

{

MyDel del = new MyDel (Sum); // create a delegate object.

 

Console. WriteLine ("Before BeginInvoke ");

IAsyncResult iar = del. BeginInvoke (3,5, CallWhenDone, null );

 

Console. WriteLine ("Doing more work in Main ");

Thread. Sleep (500 );

Console. WriteLine ("Done with Main, Exiting ");

Console. ReadKey ();

}

}

}

 

The program output result is:

 

 

Timer:

The timer provides another formal method to run asynchronous methods repeatedly. Although there are several available Timer classes in. net bcl, here I will only introduce one of the System. Threading namespaces.

Note the following when using a Timer:

1. The timer calls the callback method after each expiration time. The callback method must be in the form of TimerCallback delegation.

2. When the timer expires, the system will enable the callback method from the thread in the thread pool, provide the state object as its parameter, and start running.

3. The Timer constructor accepts the callback method name, dueTime, period, and state as parameters. The most common constructor forms are as follows:

Timer myTimer = new Timer (MyCallback, someObject, 2000,1000 );

Note: MyCallback is the name of the callback method.

SomeObject is the object passed to the callback.

2000: dueTime indicates the first call after 2000 milliseconds.

1000 (period) indicates a call every 1000 milliseconds.

Example:

 

 

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using System. Threading;

 

Namespace thread4

{

Class Program

{

Int TimesCalled = 0;

 

Protected void Display (object state) // declare the callback method.

{

Console. WriteLine ("{0} {1}", (string) state, ++ TimesCalled );

}

 

Static void Main (string [] args)

{

Program p = new Program (); // create a class instance.

 

Timer myTimer = new Timer (p. Display, "Processing timer event",); // create a Timer class object.

Console. WriteLine ("Timer start ");

Console. ReadKey ();

}

}

} The following output is generated within five seconds before the code is disabled:

 

 

The above is the summary of the multi-threaded programming knowledge, written for one afternoon. Today is my 27-year-old birthday. I have to prepare to invite my colleagues to dinner. I also hope that I will be healthy and work well in the new year.

 

 

 


Author's permanent Wheat

Related Article

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.