C # basics-Use of events,
I. What is an event?
Events are operations that can be recognized by controls. For example, click the OK button and select a single button or check box. Each control has events that you can recognize, such as events such as loading, clicking, and double-clicking forms, text change events in the editing box (text box), and so on. Events are invisible everywhere in desktop applications, such as winform and WPF.... Second, events are generated based on delegation.
Ii. basic use of events
1. Event declaration:In fact, as with the delegate, there is only one more Event. ShowMsg provides the ShowMsgHandler function.
Notes:1. The delegate can depend on a class or a domain name space (C # basics --- the use of the Delegate, which I have mentioned), and the event must depend on a class. No.
2. The delegate can use the = sign, and the event can only use the + or-to add and delete methods. When the event is empty, no error is returned when you call the [-] method.
public delegate void ShowMsgHandler(string str);public event ShowMsgHandler ShowMsg;
2. Basic use of events:In fact, the basic usage is similar to that of delegation. It should be noted that you can determine whether a method has been registered to an event or delegate by determining whether it is Null. Sometimes it is brave to judge whether the event should be triggered. Second, we also found that the first time an event was added to a method, we directly used the "+" number, instead of using the "=" number for the first time as the delegate, and the "+" number will be used later.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace SpongeBobCoder.EventTest{ public delegate void ShowMsgHandler(string str); public class Program { public static event ShowMsgHandler ShowMsg; public static void ShowName(string str) { Console.WriteLine("My Name is {0}", str); } public static void Main(string[] args) { Console.WriteLine(ShowMsg == null); ShowMsg += ShowName; ShowMsg("SopongeBob"); Console.WriteLine(ShowMsg == null); Console.ReadKey(); } }}
3. Why event:
In fact, from the above point of view, the event is similar to the Commission. There is no difference in usage, but why do we need to use delegation? The document I saw on Codeplex is quite good. Http://www.codeproject.com/Articles/7316/Events-and-Delegates; younger brother English is not good, good English to look at the original, I probably understand: Like an App developed by a project team, there must be a project manager, the project manager has many employees working for him. In fact, the manager is like a delegate, and every employee in the job is like a delegate registration method. After the project development is completed, it is handed to the user and installed by the user. However, the user finds Software defects and needs improvement. At this time, the user will not directly contact the project manager of the development team. Opinions are often sent to the maintenance department, and the maintenance department informs the project manager of the corresponding development group. The process of notification is called an event. Events can be used for better encapsulation and delegate management. Personally, this is why events are based on specific classes. Different types of events can be bound to the same delegate to register different methods.
3.1 What is the Publisher class first? The class has an event CalculatorEvent and a method DoSomething. If the event is added with a method, It will be executed.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace SpongeBobCoder.EventTest{ public class Publisher { public event CalculatorHandler CalculatorEvent; public void DoSomething(double num1,double num2) { if (CalculatorEvent != null) { CalculatorEvent(num1, num2); } } }}
3.2 then let's look at the Program class. The Main method declares two Publisher objects, A and B. AddNum and SumNum are added respectively. The running result is 3 and-1. You can use a Publisher class to manage delegates.
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace using gebobcoder. eventTest {public delegate void CalculatorHandler (double num1, double num2); public class Program {public static void AddNum (double num1, double num2) {Console. writeLine ("sum of two numbers: {0}", num1 + num2);} public static void SubNum (double num1, double num2) {Console. writeLine ("the difference between the two is: {0}", num1-num2);} public static void Main (string [] args) {Publisher pubA = new Publisher (); publisher pubB = new Publisher (); pubA. calculatorEvent + = AddNum; pubB. calculatorEvent + = SubNum; pubA. doSomething (1, 2); pubB. doSomething (1, 2); Console. readKey ();}}}
Iii. Use of events
1. Exception Handling:You can register multiple methods for an event. But what if one of the methods throws an exception. If the current execution program is interrupted, the subsequent registration method cannot be executed. The problem arises. What methods can be used to solve this problem? Method 1: Make sure that the registered method does not have an exception, which is unpredictable. Method 2. Eat all registered method exceptions. Microsoft provides two methods: GetInvocationList and DynamicInvoke:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace using gebobcoder. eventTest {public class Publisher {public event CalculatorHandler CalculatorEvent; public void DoSomething (double num1, double num2) {if (CalculatorEvent! = Null) {Delegate [] delArray = CalculatorEvent. getInvocationList (); // obtain all delegate methods. foreach (Delegate del in delArray) {try {object obj = del. dynamicInvoke (num1, num2); // obj is used to obtain the return value of each method. If the declared delegate has no return value, obj = null Console. writeLine (obj = null);} catch (Exception e) // eat the Exception {Console. writeLine (e. innerException. message );}}}}}}
2. asynchronous call:For the previous registration time, they were all executed sequentially. How can we implement asynchronous execution without mutual interference between registration? In fact, Microsoft provides a BeginInvoke method to solve this problem.
Public IAsyncResult BeginInvoke (InvokeArgs invokeArgs, // This part is for entrusting AsyncCallback callback, // callback method. After the registration method is executed, will execute the callback method Object userState // The parameter passed)
The above may be a little difficult to understand. Let's take a look at the Code:
Program class: The AddNum method has a latency of 5 seconds. No latency is added for SubNum. The registration sequence is AddNum and SubNum.
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. threading; namespace using gebobcoder. eventTest {public delegate double CalculatorHandler (double num1, double num2); public class Program {public static double AddNum (double num1, double num2) {Thread. sleep (TimeSpan. fromSeconds (5); Console. writeLine ("sum of two numbers: {0}", num1 + num2); return num1 + num2;} public static double SubNum (double num1, double num2) {Console. writeLine ("difference between two numbers: {0}", num1-num2); return num1-num2;} public static void Main (string [] args) {Publisher pubA = new Publisher (); pubA. calculatorEvent + = AddNum; pubA. calculatorEvent + = SubNum; pubA. doSomething (1, 5); Console. readKey ();}}}
Publisher class: Pay attention to the red method. The first two parameters correspond to the delegate. The following MyCallBack is the callback method,
Using System; using System. collections. generic; using System. linq; using System. runtime. remoting. messaging; using System. text; using System. threading. tasks; namespace using gebobcoder. eventTest {public class Publisher {public event CalculatorHandler CalculatorEvent; public void DoSomething (double num1, double num2) {if (CalculatorEvent! = Null) {Delegate [] delArray = CalculatorEvent. getInvocationList (); // obtain all delegate methods. foreach (Delegate del in delArray) {try {CalculatorHandler handler = del as CalculatorHandler;IAsyncResult myResult= Handler. BeginInvoke (num1, num2, MyCallback, "Method execution completed, callback successful" + handler. Method. Name );// Console. WriteLine ("mongogebob"); if this code is not annotated, the output of this code is executed first before other codes are output. I don't know why} catch (Exception e) // eats the Exception {Console. writeLine (e. innerException. message) ;}}} public void MyCallback (IAsyncResult asyncResult) {AsyncResult result = (AsyncResult) asyncResult; CalculatorHandler handler = (CalculatorHandler) result. asyncDelegate; Console. writeLine (asyncResult. asyncState); Console. writeLine ("the obtained execution result is: {0} \ n", handler. endInvoke (asyncResult ));}}}
Running result: in fact, SubNum is executed first, and the asynchronous effect has been achieved. the return value of the delegate is also obtained through EndInvoke In the callback function.
Codezip: http://files.cnblogs.com/FourLeafCloverZc/CSharp.zip
Summary:In the past, I was not clear about the events. I remember that at the time of winform, we had to use Invoke to obtain data from different threads. Otherwise, we would always prompt that the thread is not safe. I found two problems in this blog. You need to answer them.
1. I noted a piece of code in the Code for asynchronous calls. In fact, I found a problem, if the Console. writeLine ("mongogebob"); without annotation, the running condition is that two rows ("mongogebob") are output first and then the running result is output. I don't know why. Please give me some advice.
2. If the input parameter of the following code is, no error is reported. The running result is an infinite division of two numbers. We should report an exception where the divisor cannot be 0.
Public static void DivNum (double num1, double num2) {Console. WriteLine ("division of two numbers: {0}", num1/num2 );}
A simple program of C language Bubble Sorting
Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}
--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.
Bubble Sorting
1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.
(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.
(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.
2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49
3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.
(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">
A simple program of C language Bubble Sorting
Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}
--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.
Bubble Sorting
1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.
(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.
(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.
2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49
3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.
(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">