C # basic --- use of events

Source: Internet
Author: User

C # basic --- use of events
1. What are event events that can be recognized by controls? For example, click OK to select a single-choice 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, there is only one more Event than delegate. ShowMsg provides the ShowMsgHandler function. Notes: 1. The delegate can depend on a class or a domain name space (C # basis-the use of the Delegate, which I 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. Copy the code using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace using gebobcoder. 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) {Conso Le. writeLine (ShowMsg = null); ShowMsg + = ShowName; ShowMsg ("SopongeBob"); Console. writeLine (ShowMsg = null); Console. readKey () ;}} copy code 3. why use Event: in fact, the event is similar to the delegate. 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, the System will copy the code 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) {CalculatorEvent (num1, num2) ;}}} copy code 3.2 and check 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. Copy the code 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) {Conso Le. 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 () ;}} copy code 3: Use of the Event 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. The System eats all registered method exceptions. Microsoft provides two methods: GetInvocationList and DynamicInvoke: copy the code 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) ;}}}} copy Code 2. asynchronous call: the previous registration time is executed in sequence. How can we implement asynchronous execution without mutual interference between various registrations? In fact, Microsoft provides a BeginI The nvoke method can 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 bit difficult to understand. Let's take a look at the code: Program class: AddNum method has a latency of 5 seconds. No latency is added for SubNum. The registration order is AddNum. SubNum copies the code 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 () ;}} copy the code publisher class: Pay attention to the red method, the first two parameters It corresponds to the delegate. The following MyCallBack is the callback method. Copy the code 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 commented out, the output of this code is executed first before other code is 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) ;}} copy the code running result: in fact, the first execution is S. UbNum has achieved the asynchronous effect, in which the return value of the delegate is also obtained through the EndInvoke callback function. Codezip: http://files.cnblogs.com/FourLeafCloverZc/CSharp.zip Summary: The previous understanding of the event is not clear, remember that at the time of winform cross-thread to obtain data will be obtained with Invoke, otherwise it is always prompted that the thread is not safe. I have found two problems in this blog. I need to help you solve them. 1. I have annotated a piece of code in the Code for asynchronous calling. 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 );}

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.