[reading notes] the way of Cultivation: the key points of. Net development

Time:2020-11-23

PracticeThe way:.NET developmentmain pointsIntensive lectures

Author:Zhou Jianzhi; botouxuan


Chapter 1 opens a new path: Interpretation of. Net

1.7 thinking in this chapter > position 465

1. Briefly describe the meaning and function of CTS, CLS and CLR in. Net platform.

A: CTS refers to the common type system, which is the type specification that all languages in. Net platform must comply with; CLS refers to the common language specification, which is the language specification that all languages in. Net platform must comply with; CLR refers to the common language runtime, which is a virtual machine, and all managed code in. Net platform needs to run in CLR, Think of it as another operating system.

 

Chapter 2 from a strategic perspective: combing programming conventions

2.2 relationship between method and thread > position 519

As long as we determine that two methods will only run in the same thread, then the two methods can not be executed at the same time, regardless of the location of the method.

It can only be executed one after the other. At this time, we don’t need to consider whether the thread of the common resource accessed in the method is safe.

 

2.7 thread safety > position 595

If the operation of an object (such as calling its method or assigning a property) is a non atomic operation, that is, the operation may be suspended before it is completed. At this time, if another thread starts to run and also operates on the object and accesses the same method (or property), then one may appear Problem: before the previous operation is finished, the latter operation starts, and the two operations are confused together. When multiple threads access an object at the same time, if each execution results in different results or even exceptions, the object is “non thread safe”. There are many factors that cause an object to be non thread safe. In addition to the previously mentioned interruption of non atomic operations in the middle of execution, there is another situation that is caused by multiple CPUs. That is, even if the operation is not interrupted, because multiple CPUs can truly realize the simultaneous operation of multiple threads, there may be a “yes” problem The operation of the same object is chaotic, as shown in Figure 2-4.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图

 

2.7 thread safety > position 627

In WinForm programming, we often encounter the exception “do not access the control in the thread that created the control”. The reason is that almost all operations on UI controls are thread safe (partially). Generally, UI controls can only be operated by UI thread, and all other operations need to be delivered to UI thread for execution. Otherwise, as mentioned above, the program will be abnormal or unstable.

You can use the control. InvokeRequired property to determine whether the current thread is the thread that creates the control (UI thread). If so, the property returns false, and the UI control can be operated directly. Otherwise, it returns true and cannot operate the UI control directly.

Note: control contains several thread safe methods and properties. The common ones are control. InvokeRequired property, control. Invoke method, control. BeginInvoke method (asynchronous version of control. Invoke), control. Endinvoke method and control. CreateGraphics method. These properties and methods can be used in non UI threads, and cross thread access to these methods and properties will not cause program exceptions.

 

2.8 calls and callbacks > position 661

The callback in the development of. Net platform is mainly realized through delegation. A delegate is a proxy responsible for invoking methods.

 

2.9 managed and unmanaged resources > location 666

The unmanaged resources used by objects in. Net mainly include I / O stream, database connection, socket connection, window handle and other resources directly related to the operating system.

 

2.13 protocol > location 751

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(1)

Figure 2-11 network layer 7 protocol

 

Chapter 3 Foundation of programming: data type

3.1 reference type and value type > position 844

Generally, value types are divided into the following two parts.

(1) Simple value types: including. Net built-in types such as int, bool, long, etc. They are also structures.

(2) Compound value type: a structure defined by the structure keyword, such as system. Drawing. Point. Composite value types can be composed of simple value types and reference types.

 

3 assignment and copy > position 1118

The difference between the assignment of reference type, shallow copy and deep copy is shown in Figure 3-15.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(2)

 

The difference between value type assignment, shallow copy and deep copy is shown in Figure 3-16.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(3)

 

The process of object deep replication is shown in Figure 3-17.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(4)

 

3.3 assignment and copy > position 1155

Net can use the technology of “serialization and deserialization” to realize the deep replication of objects. As long as the types of a type and all its members are marked as “serializable”, then the object of this type can be serialized to the byte stream first, and then the byte stream can be de sequenced into a copy of the source object. In this way, there is no association between the source object and the replica, thus achieving the effect of deep replication.

 

Chapter 4 birds of a feather flock together: objects also have life

4.1 heap and stack > position 1235

Stack is mainly used to record the running process of the program, it has strict storage and access order; while the heap mainly stores some data generated during the program running, almost no concept of order.

 

4.1 heap and stack > position 1269

The essence of heap and stack is a block of memory.

 

4.2 birth and death of objects in the heap > position 1272

The objects in the stack are automatically stored and removed by the system. Under normal circumstances, they are not related to our program development.

 

4.2 birth and death of objects in the heap > position 1354

Use the object’s destructor with caution. Destructor method is called by CLR, which is not controlled by program, and it is easy to regenerate object. The destructor method can hardly be used for any purpose other than managing unmanaged resources.

 

4.3 manage unmanaged resources > location 1381

The GC. Suppressfinalize method requests the CLR not to call the destructor method of this object. The reason is very simple. Since the unmanaged resources have been released, there is no need for the CLR to continue to call the destructor method.

 

Note: it is a complex process for CLR to call the destructor method of an object, which consumes a lot of performance. This is also an important reason to avoid releasing unmanaged resources in the destructor method. It is better not to call the destructor completely.

 

4.4 correctly use IDisposable interface > position 1547

If a type uses unmanaged resources, or if it contains members that use unmanaged resources, then developers should apply the “dispose pattern”: correctly implement the (indirect or direct) IDisposable interface and correctly override the dispose (bool disposing) virtual method.

 

Thinking in this chapter > position 1587

After calling the dispose() method of an object, it does not mean that the object has died. Only after GC reclaims the memory occupied by the object instance can the object be said to be dead. But usually, after calling the dispose() method of an object, because the unmanaged resources of the object are released, the object is almost in a “useless” state, and “waiting for death” is its correct choice.

 

Chapter 5 top priority: delegation and events

5.1 what is delegation in. Net > position 1625

Just like declaring a normal method, you define a delegate type by providing the method name, parameters, access modifiers, and return value, followed by the delegate keyword.

How to instantiate a delegate object after defining a delegate type? In fact, it is very simple. Just like instantiating other types of objects, we can create delegate objects with the new keyword.

 

5.1 what is delegation in. Net > position 1655

When calling a method with a delegate, we can directly use the format “delegate object (parameter list);”, which is equivalent to “delegate object. Invoke (parameter list)”.

Another way to assign a delegate is: delegate object = method.

 

How to make a delegate call two or more methods at the same time? The answer is to attach multiple methods directly to the delegate object using the addition assignment operator (=).

 

5.1 what is delegation in. Net > position 1744

The implementation principle of the “linked list” structure inside the delegation is different from that of the unidirectional list. Instead of associating with subsequent delegates through the next reference, it stores all delegates in an array, as shown in Figure 5-6.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(5)

Each delegate type has a public getinvocationlist() method that can return all delegates attached to the delegate object, that is, the array list part in Figure 5-6. In addition, we usually do not distinguish between a delegate object and a delegate list. When we mention a delegate object, it is likely to represent a delegation linked list, which is similar to the principle when a one-way linked list contains only one node.

 

5.1 what is delegation in. Net > position 1781

Delegates, like string types, are immutable. In other words, once the delegate object is created, the object can no longer be changed. How do we explain how to attach a delegate to another delegate to form a delegation list? In fact, this is similar to the string. Toupper() procedure. When we attach or remove a delegate, a new delegate will be generated. These operations will not change the original delegate object.

 

5.1 what is delegation in. Net > position 1821

There are two ways to call the code written by framework users. One is oriented to abstract programming, that is, to avoid a specific type of reference in the framework as far as possible, but use abstract base class reference or interface reference instead. As long as the types written by framework consumers derive from abstract base classes or implement interfaces, the framework can call them correctly.

Another way for the framework to call the framework consumer code is to use a delegate, which passes the delegate as a parameter (variable) to the framework, and the framework calls the method through the delegate.

 

5.2 relationship between event and delegation > position 1860

In. Net, another access level between public and private is proposed: when defining delegate members, the event keyword is given to modify it. Public delegate members with event keyword modification can only carry out attachment and removal operations outside the class, while the calling operation can only occur on types Inside.

 

We call the delegate with the event keyword set in the class “event”. “Event” is essentially the entrusted object. The occurrence of the event limits that the delegate call can only occur inside a type, as shown in Figure 5-12.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(6)

In Figure 5-12, because the delegate in the server is decorated with the event keyword, the delegate can only be called inside the server, and can only be used to attach and remove methods externally. When a certain condition is met, the server will call the delegate internally. This time is not controlled by the client, but determined by the system (server). So most of the time, events act as callbacks in the program.

 

Calling a delegate decorated with the event keyword is also called “fire event.”. Among them, the caller (server in Figure 5-12) is called “event publisher”; the callee (client in Figure 5-12) is called “event registrant” (or “event observer”, “event subscriber”, etc., which are collectively referred to as “event registrant”) in this book; the process of additional delegation is called “event publisher” “Registration event” (or “binding event”, “listening event” and “subscription event” are collectively referred to as “registration event” in this book); the process of removing delegation is called “logoff event”. Methods called through a delegate are called event handlers.

 

5.3 using event programming > location 1940

When a delegate chain is called, if an exception is thrown by the corresponding method of a delegate, the remaining delegates will not be called. This is easy to understand. The method is called in sequence. If one of them throws an exception, the rest will be skipped. In order to solve this problem, it is not enough to put the code that fires the event in the try / catch block. We also need to call each delegate step by step and put the calling code of each step in the try / catch block.

 

5.3 using event programming > location 1967

In addition to the naming of the event itself, the naming of the delegate type to which the event belongs also has a standard format. Generally, delegates are named in the format of “event name EventHandler”. Therefore, the delegate type name corresponding to the newemail received event mentioned above should be “newmailreceivedeventhandler”). When the event is fired, some parameters will be passed. These parameters are generally inherited from the EventArgs type (the latter is the pre-defined type of the. Net framework) and named after “event name EventArgs”. For example, the parameter type name passed by the newemail received event should be “newmailreceivedeventargs”.

 

5.3 using event programming > location 2004

The reason to put the code for firing events in a separate virtual method is to enable subclasses derived from the type (email manager) to override virtual methods, thus changing the logic of firing events.

 

Virtual methods are generally named as “on event name”. In addition, the virtual method in the code must be defined as “protected” because it is likely that the virtual method of the base class will be called in the derived class.

 

5.3 using event programming > position 2039

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(7)

Figure 5-13 the role of attributes and events

 

Weak delegation > position 2077

In event programming, the delegate’s target member is a strong reference to the event registrant. If the event registrant does not log off the event, the strong reference target will always exist, and the event register memory in the heap will never be recycled by the CLR. This is almost impossible for developers to find out.

 

For example, the A in “a = new a();” is called “explicit strong reference”. Similar to the implicit strong reference contained in a delegate, we call it “implicit strong reference”.

A weak reference and an object instance belong to a “weak association” relationship, which is different from the relationship between a strong reference and an object instance. Even if a weak reference in the program points to an object instance in the heap, the CLR will still regard the object instance as a recycling target. Before using a weak reference to access an object instance in a program, you must first check whether the CLR reclaims the memory of the object. In other words, when an object instance in the heap has only a weak reference pointing to it, the CLR can reclaim its memory. With weak reference, whether the objects in the heap can be accessed is in the hands of both the program and the CLR.

Creating a weak reference is very simple. Use the WeakReference type and pass a strong reference to its constructor as a parameter.

 

Weak delegation > position 2105

In the process of programming, it is difficult to manage strong references, which results in unnecessary memory overhead. In particular, the “implicit strong reference” mentioned above is not easy to find their existence in the process of use. Weak references are particularly suitable for objects that are not program dependent, that is, those whose life span is not controlled by the program. For example, in event programming, the event publisher is not very concerned about the existence of the event registrant. If the registrant is present, it will fire the event and notify the registrant; if the register has been reclaimed by the CLR, it will not be notified, which will not affect the operation of the program.

 

Weak delegation > position 2109

As mentioned earlier, a delegate consists of two parts: a target member of the object type, representing the owner of the called method; if the method is a static method, the target is null; and the method member of the methodinfo type, representing the called method. Because the target member is a strong reference, as long as the delegate exists, the owner of the method will always be in the heap and cannot be recycled by the CLR. If we replace the target strong reference in the delegate with a weak reference, then whether the delegate exists or not, it will not affect the method owner’s memory recycling in the heap. In this way, before using a delegate to call a method, we need to determine whether the owner of the method has been reclaimed by the CLR. We call the delegate after replacing the target member with a weak reference as “weak delegate”. The definition code of the weak delegate is as follows:

//Code 5- 26 
class WeakDelegate 
{ 
    WeakReference _weakRef; //NO. 1 
    MethodInfo _method; //NO. 2 
    
    public WeakDelegate(Delegate d) 
    { 
        _weakRef = new WeakReference(d.Target); 
        _methodInfo = d.Method; 
    } 
    
    public object Invoke( param object[] args) 
    {
        object obj = _weakRef.Target; 
        if(_weakRef.IsAlive) //NO. 3 
        { 
            return _method.Invoke(obj, args); //NO. 4 
        } 
        else 
        { 
            return null; 
        } 
    } 
}

 

Weak delegation transforms the relationship between the delegate and the owner of the called method from “strong association” to “weak association”. The life cycle of the method owner in the heap is no longer controlled by the delegate, as shown in Figure 5-16, which is the structure of weak delegation.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(8)

The weakdelegate type in the sample code in this section does not provide methods such as delegate. Combine and delegate. Remove to operate the delegation list. Of course, it does not have the function of weak delegation list. These functions can be implemented by imitating the structure of one-way linked list, and each weak delegate is regarded as a node in the list. The method can refer to the one-way linked list mentioned in section 5.1.2.

 

5.5 review of this chapter > position 2151

Delegate has three functions: first, it allows methods to be passed to other modules as parameters; second, it allows us to call multiple methods with the same signature at the same time; third, it allows us to call any method asynchronously. These three roles establish the absolute importance of delegation in. Net programming.

 

Chapter 6 thread upgrade: asynchronous programming model

6.1 necessity of asynchronous programming > position 2171

In general, calling a method conforms to such a rule: after the calling thread starts to call method a and before a returns, the calling thread cannot get control of program execution. In other words, the code behind method a cannot be executed until a returns. This method of calling is called “synchronous call”; on the contrary, if the calling thread still retains control before the call returns and can continue to execute the following code, then this calling method is called “asynchronous call”.

 

Synchronous calls are also called “blocking calls” by some scholars, while some relative asynchronous calls are called “non blocking calls”.

 

6.2 asynchronous call of delegate > position 2202

In theory, any method can be called asynchronously after being wrapped by a delegate.

 

Each delegate type defined by the. Net compiler automatically generates two methods: BeginInvoke and endinvoke. These two methods are specifically used to call delegates asynchronously.

BeginInvoke returns an IAsyncResult interface type that uniquely distinguishes an asynchronous calling procedure. BeginInvoke can return as soon as it is executed without blocking the calling thread. Endinvoke means to end an asynchronous call to a delegate, but this does not mean that it can interrupt the asynchronous calling process. If the asynchronous call has not finished, endinvoke can only wait until the asynchronous calling process is finished. In addition, if the delegate has a return value, we must get the return result through endinvoke.

 

6.2 asynchronous call of delegate > position 2233

After the start of the delegate asynchronous call, the system finds an idle thread in the thread pool to execute the delegate.

 

6.2 asynchronous call of delegate > position 2296

When calling a delegate asynchronously, because the method is actually running in other threads (a thread in the thread pool, not the current calling thread), the current thread cannot catch the exception. How can we know whether there will be an exception in the asynchronous call? The answer lies in the endinvoke method. If the asynchronous call procedure has an exception, the exception will be thrown when we call the endinvoke method. So when we call the endinvoke method, we must put it in the try / catch block.

 

6.3 non delegate asynchronous calls > position 2358

The types that provide asynchronous methods in. Net include stream (or its derived class), socket (or its derived class) and SqlConnection type for accessing database. They are used in a similar way to the BeginInvoke and endinvoke methods of a delegate, except that the naming is different. They are basically in the form of “begin operation” and “end operation”. For example, FileStream. Beginread means to start an asynchronous read operation, while FileStream. Endread means to end an asynchronous read operation.

 

6.6 thinking in this chapter > position 2446

The effect of asynchronous programming is similar to that of multithreading programming, which is to execute code in parallel and to process tasks at the same time. In asynchronous programming, the system allocates threads through the thread pool, which does not need manual intervention. The logic of asynchronous programming is complex and difficult to understand. However, in multithreading programming, human control is needed completely, which is relatively flexible.

 

Chapter 7 reusable code: the context of components

7.1 component in. Net > position 2457

In. Net programming, we implement (directly or indirectly) System.ComponentModel.IComponent The type of interface is called “component”,

 

7.1 component in. Net > position 2472

Components and controls are not equal. Components contain controls, and controls are just a category of components.

 

7.1 component in. Net > position 2477

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(9)

Figure 7-2 relationship between controls in Windows Forms

 

All controls are derived from the control class, which belongs to components, so all controls have the characteristics of components.

Both components and controls are reusable code sets that implement the IDisposable interface and follow the dispose pattern described in Chapter 4. If a type uses unmanaged resources, it can implement the IDisposable interface. Then why put forward the concept of component in. Net programming?

It can be said that the purpose of doing this is to realize the “visual development” of the program, that is to say, “what you see is what you get”. In a development environment like visual studio, all “components” can be visually designed. In other words, as long as the type we define implements the icomponent interface, then in the development phase, the type can appear in the form designer, and we can use the form designer to edit its properties and give it Register events. It can also be recognized by other components in the form designer.

 

7.2 container component service model > location 2499

In. Net programming, to implement (directly or indirectly) system ComponentModel.IContainer The types of interfaces are called logical containers (hereinafter referred to as “containers”).

Containers are for components.

There is a default implementation of icontainer interface in. Net framework: system ComponentModel.Container Type, which implements methods and properties in the icontainer interface by default.

 

7.2 container component service model > location 2514

Traditional containers simply organize data together in space, and cannot provide support for data interaction. The logical container discussed in this chapter, in a sense, is more advanced. It can support the communication between components (logical elements), and components are no longer independent. In addition, it can provide some services directly to components. The relationship between physical container and logical container and element is shown in Figure 7-4.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(10)

The elements in the physical container can not communicate with each other, and the physical container can not provide services for its internal elements; the components in the logical container can be used as a bridge to exchange data; at the same time, the logical container can also provide services for each component. The so-called service means that the logical container can provide some access support for components. For example, if a component needs to know how many components are contained in its container, it can make a request to the container. When the container receives the request, it returns an interface to get the total number of components.

 

In section 7.1.1 of this chapter, we mentioned that there is an attribute of type isite in the icomponent interface. At that time, it was said that it played a role of “positioning”. Now it seems that the link between the component and the container is it, and the component is connected with the container to which it belongs through this attribute.

 

7.2 container component service model > location 2574

The three types of component, site and container contain getservice to obtain service. Now we can sort out the process of the component requesting service from the container, as shown in Figure 7-6.
[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(11)

 

Note: when a container adds a component (execute container. Add), the site property of the component will be initialized to associate the component with the container. Only after this process occurs can the component obtain the service of the container.

 

7.2 container component service model > location 2601

When we drag a control to the form designer, code like “new button();” will be executed to instantiate a component instance in memory.

 

7.2 container component service model > location 2655

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(12)

Figure 7 – 10 components and generated source code in form designer

In Figure 7-10, a button control that we drag and drop into the designer is shown on the left. In this process, the form designer will not only instantiate a button control (in form2 on the left of the figure), but also generate the code on the right for us.

 

7.3 design time and operation time > position 2672

Any component has two states: design time and runtime.

There are two ways to determine the current state of a component.

(1) Determine the designmode property of the component. Each component has a bool type designmode property. As it literally means, if the property is true, the component is currently in the design time state; otherwise, the component is in the runtime state.

(2) Request a service randomly and check whether the returned service interface is null. As mentioned earlier, when a component does not belong to any container, the service it requests through the getservice method must return null.

 

Note: (1) (2) methods are not suitable for nested components, because the form designer will only set the designmode property value of the outermost component to true.

One way to solve this problem is to check the name of the current process through the process class. See if it contains the string “devenv.”. If “currentprocess ()” is in the development environment of “getprocessins (), that is, if it is in the development environment of” getprocessins (), then it is in the development environment of “getcontains ()). This method also has a disadvantage. Obviously, if we are not using the visual studio development environment (that is, the process name does not contain devenv), or our own program process name itself already contains devenv, what should we do?

 

When developing some components that need authorization, two states of components can be used. These components that need authorization are usually charged to developers. Therefore, when developers use these components to develop the system (in the development stage), there should be an authorization entry, and when the program is running, there should be no authorization interface.

 

7.4 controls > position 2776

Whether it is a composite control, an extended control or a custom control, we can rewrite the window procedure of the control: the wndproc virtual method, which can contact the windows message from the root. This practice is not the patent of the custom control.

 

Chapter 8 classic emphasis: desktop GUI framework

8.2 structure of Win32 Application > position 2841

The program is unable to directly identify the input information of the user’s keyboard or mouse. These inputs must be converted into fixed format data by the operating system before they can be used by the program.

In Windows programming, we call the fixed format data converted by the operating system as windows message. Windows message is a predefined data structure (such as structure in C), which contains message type, message receiver and message parameters. We also call the structure of getting windows message in the program as windows message loop. In a loop, for example, the message is sent to the windows program to process the message without stopping.

 

8.2 structure of Win32 Application > position 2895

In windows, messages are actually divided into two categories. One is stored in the message queue, which can be processed by the window process after being retrieved by the message loop. This kind of message is called “queued message”. This kind of message mainly includes user’s mouse and keyboard input message and drawing message WM_ Paint, exit message WM_ Quit and time message WM_ TIMER。 The other is that they do not need to be stored in the message queue or go through the message loop. They are directly passed to the window procedure and processed by the window process directly. This kind of message is called “non queued message”. When the operating system wants to tell the window that something has happened, it will send a non queue message to the window. For example, when we use setwindowpos API to move the window, the system will automatically send a WM_ Windows change message to the window window process, tell it the location has changed.

 

8.4 Windows Forms framework > location 3148

In Windows Forms framework, control is taken as the base class, and almost all other controls related to form display are derived from it; the wndproc virtual method in the control class is the window process we are familiar with in the Win32 development mode. In addition, as mentioned above, forms and controls are essentially the same thing, but they have different properties. Therefore, we can see that the form class form indirectly derives from the control class.

 

WinForm program contains three parts: message queue, UI thread and control.

 

8.5 structure of WinForm program > position 3180

In the program. CS file of each WinForm program, there is a main method, which is the entry method of the program. Each program starts with the main method as the entry point to create a thread, which is the UI thread. You may ask why there is no message loop in the UI thread? That’s because there is always a method like application. Run in the main method, and the message loop is hidden inside the method (see the next section for details). Theoretically, a program can have multiple UI threads, and each thread has its own message queue (maintained by the operating system), message loop, form and other elements, as shown in Figure 8-13.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(13)

 

Due to the complexity of data exchange between UI threads, a program usually contains only one UI thread without special requirements.

 

8.5 structure of WinForm program > position 3265

Understanding of UI thread:

① A program can contain multiple UI threads. We can create a new common thread through the system. Threading. Thread class, and then call the application. Run method in the thread to open the message loop;

② When a UI thread ends (the number of message loops in the thread is “0”), the application. Threadexit event will be fired to inform the UI thread to terminate. Only when all UI threads have ended (the total number of message loops in the program is “0”), the application. Exit event will be fired to tell the application to exit.

Finally, let’s take a look at the structure of the message loop in Windows Forms, as shown in Figure 8-14.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(14)

 

8.5 structure of WinForm program > position 3319

Windows Forms framework encapsulates the form and window procedure together. The “wndproc” virtual method in the control (or its derived class, the same below) class is the window procedure of the control. The reason why WINDOWS procedures are declared as virtual methods is that Windows Forms framework is object-oriented, which makes full use of the “polymorphism” feature in object-oriented programming. Therefore, all derivative classes of control class can override its window procedure to intercept windows messages from the source and process the windows messages they want to process.

 

The window procedure does a very important thing: it converts the window message into an event in. Net.

 

Chapter 9 communication: network programming

9.1 two socket communication modes > position 3518

(TCP) data is in order to walk in the established tunnel, then the data should follow the “first come, first arrive” rule, and the data in the tunnel is transmitted in the form of “stream”. There is no boundary between the two data sent by the sender, so the receiver needs to judge the data boundary according to the pre-defined “Protocol”.

 

9.1 two socket communication modes > position 3555

In UDP communication, data is transmitted in the form of datagram, which is sent as a whole and received as a whole. Therefore, UDP has data boundary. However, the data received by UDP is out of order. The data sent first may be received later, and those sent later may be received first or even not received.

 

9.1 two socket communication modes > position 3605

In. Net, there are five types of socket communication programming, as shown in table 9-1.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(15)

 

The relationship between tcplistener and tcpclient is shown in Figure 9-9

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(16)

In Figure 9-9, the tcplistener listens for the “connect” request from the client and returns a proxy tcpclient, which exchanges data with the tcpclient of the client.

The role of UdpClient in UDP communication is shown in Figure 9-10

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(17)

 

The networkstream type is a derived class of the system. Io. Stream class. Networkstream can only be used in TCP communication.

Socket type is a relatively basic communication type. It can realize both TCP communication and UDP communication. It can be considered that tcplistener, tcpclient and UdpClient further encapsulate the socket type.

 

9.3 implementation of UDP communication > position 3840

The reason why the data structure of the application layer protocol in TCP communication is designed in the form of byte stream, because the data in TCP communication is transmitted in the form of stream. After formatting the data in the form of byte stream, it is more convenient for the program to judge the data boundary.

In UDP communication, data is transmitted in the form of datagram, and the data received each time is complete. For the current instance of LAN instant communication, the protocol in the form of text is more convenient for program to process data. Of course, we can also design the data structure of application layer protocol in UDP communication into bytes The form of the stream.

 

Application of asynchronous programming in network programming > position 3991

Use socket. Beginsendto() method to start an asynchronous sending process, and provide the method with a callback parameter of asynccallback. Calls to this method do not block the calling thread. We can use the socket. Endsendto() method in the callback method onsend to end the asynchronous sending process, which returns the actual data length sent.

 

Application of asynchronous programming in network programming > position 4011

Asynchronous programming can also implement loop receiving data, but we can’t see the explicitly created thread or the loop statement like while.

 

9.6 thinking in this chapter > position 4062

All communication protocols are essentially data structures. Both sides of communication must send or receive (analyze) data in the form specified by this data structure.

The communication based on TCP protocol needs to establish a connection before data interaction, which is similar to making a phone call. This communication mode ensures the correctness and reliability of data transmission. Communication based on UDP protocol does not need to establish a connection before data transmission, similar to SMS. This communication mode can not guarantee the correctness of data transmission.

 

Chapter 10 power source: Pump in code

10.2 common “pump” structure > position 4150

The UI thread of the desktop program contains a message loop (which, to be exact, should be a while loop). The loop continuously gets windows messages from message queue, and finally transfers windows messages to window procedures by calling corresponding window procedures.

 

10.2 common “pump” structure > position 4179

Every time a request is made to the web browser, a connection must be made to the web server. After the processing of the web server-side request is finished, the connection is closed immediately. The next time the browser sends an HTTP request, it must re-establish a connection with the server. It can be seen that the HTTP protocol we are talking about is for no connection. Specifically, the web server only processes one request at a time. After processing the request, the connection is closed. The browser is in the “disconnected” state from the end of the previous request to the beginning of the next request. Therefore, the HTTP protocol is called “HTTP Protocol” “Connectionless” protocol.

In addition to maintaining a persistent connection with the browser, the web server does not save the browser’s state. In other words, the same browser requests the same web server twice in succession, and the latter will not keep the processing result of the first request to the second request stage; if the second request needs to use the processing result of the first request, then the browser must return the processing result of the first time to the server.

 

Chapter 11: patterns and principles

11.1 design mode of software > position 4308

The operation of the program means that there is constant data exchange between modules and between objects. The observer mode emphasizes that when the state of a target changes (or meets a certain condition), it will actively send a notice to inform other objects interested in the change. The notifier is called the subject and the notifiee is called the observer,

 

11.1 design mode of software > position 4358

One of the most frequently used patterns is the observer. The reason is simple, “observer mode” separates framework code from code written by framework users. It is the concrete means to realize the “don’t call us, we will call you”, and the “Hollywood principle” is strictly observed by all frameworks.

 

11.1 design mode of software > position 4361

In the Windows Forms framework, it can be said that “observer mode” is everywhere. The “observer mode” in Windows Forms framework is not implemented by “interface concrete”, but more by using “delegate event” in. Net. This has been explained in Chapter 8 when talking about the WinForm program structure. For example, when a control processes a Windows message, it will eventually notify the event registrant in the form of “event”. Then the “event registrant” here is the “Observer” in the observer mode, and the control is the “subject” in the observer mode.

It can be considered that the event publisher is equal to the “subject” in the observer pattern, while the event registrant is equal to the “Observer” in the observer pattern,

 

11.1 software design mode > position 4397

According to the role of various design patterns, 23 common design patterns are divided into three categories, as shown in table 11-1.

[读书笔记] 《修炼之道:.NET 开发要点精讲》插图(18)

 

Thinking in this chapter > position 4605

The five principles and their full English names are as follows.

① Single responsibility principle.

② Open closed principle.

③ Liskov Substitution Principle.

④ Interface segregation principle.

⑤ Dependency inversion principle.

 

Chapter 12 the inevitable embarrassment: Code dependency

12.1 start from object oriented > position 4738

Class inheritance emphasizes the relationship of “I am (is – a)”, derived class “is” base class (note that “yes” here represents derived class has the characteristics of base class), while interface inheritance emphasizes “can do” relationship, which realizes the type of interface and the behavior ability specified in the interface (therefore, when the interface is named The suffix is “able”.

 

12.1 start from object oriented > position 4743

When using inheritance, the following guidelines should be followed.

(1) Strictly abide by the “Richter substitution principle”, that is, where the base class appears, the derived class must appear. Therefore, do not blindly use inheritance, if the two classes have no derived relationship, there should be no inheritance relationship.

(2) Because the derived class will inherit all the contents of the base class, the inheritance level of the type should be strictly controlled, otherwise the volume of the derived class will be larger and larger. In addition, inheritance is the most important factor to increase coupling, and the modification of base class will inevitably affect the derived class.

(3) Inheritance emphasizes the generality of types, not characteristics. Therefore, the parts of types are generally extracted to form a base class (abstract class) or interface.

 

12.2 inevitable code dependencies > position 4815

In order to measure the degree of dependence between objects, the concept of coupling is introduced. The higher the coupling degree is, the higher the dependency between objects is. In order to measure the independence of objects, the concept of cohesion is introduced. The higher the cohesion, the less interaction between the object and the outside world, the stronger the independence. Obviously, coupling and cohesion are two opposite and closely related concepts.

 

12.3 reducing code dependency > position 4936

In addition to the above mentioned extraction of the same part into an interface, sometimes it is necessary to extract the same part to generate an abstract base class, such as an abstract class. The interface emphasizes the same behavior, while the abstract class emphasizes the same properties, and should be used in the type design with the group level.

 

12.3 reducing code dependency > position 4987

The dependency generated by attributes (attribute injection) is more flexible, and its validity period is generally between “construction injection” and “method injection”.

In many cases, three kinds of dependency injection methods can be used in combination, that is, “construct injection” can be used to make the dependency relationship between the dependent and the dependent, and then “attribute injection” can be used to change the dependency relationship between them. It should be noted that dependency injection is based on dependency inversion.

 

Code dependency > position 4998 of 12.4 framework

Note: “control transformation, dependency inversion, and dependency injection are three different concepts. “Control transformation” emphasizes the transfer of program control right and pays attention to software operation process; “dependency inversion” is a theoretical guiding ideology to reduce code dependence, which focuses on software structure; “dependency injection” is a specific way to realize dependency relationship between objects, which focuses on programming.

“Control transformation” is also called “Hollywood principle”, which suggests that the relationship between framework and developer’s code is don’t call us, we will call you, that is, the initiative of the whole program is in the hands of the framework.

 

Thinking in this chapter > position 5022

How to explain the word “inversion” in the principle of “reliance on inversion”?

A: In normal logical thinking, it is natural and natural for high-level modules to rely on low-level modules. However, the “dependency inversion principle” suggests that all high-level modules should not directly rely on the underlying modules, but should rely on an abstraction. The word “inversion” here does not mean “reverse” (that is, the underlying module relies on the high-level module in turn). It just shows that the order of dependence in normal logical thinking has changed, and all things that violate normal thinking are called “inversion”.

 

 

Recommended Today

Interviewer: young man, what do you think of the principle of distributed system

1 Concept 1.1 model 1.2 copies 1.3 indicators for measuring distributed systems 2. Principle of distributed system 2.1 data distribution 2.2 basic copy agreement 2.3 lease mechanism 2.4 quorum mechanism 2.5 log technology 2.6 two phase submission protocol 2.7 MVCC 2.8 Paxos protocol 2.9 CAP 1 Concept 1.1 model node In a specific project, a […]