. NET work Preparation--03 advanced knowledge

Source: Internet
Author: User
Tags emit net thread

(OBSOLETE)

Advanced features, multithreaded programming, unit testing;

Part I.. NET Advanced Features
1. Delegate: Provide a secure function callback mechanism;
* Rationale: Similar to function pointers in C + +; security--it is just like all other. NET members, and any delegate is a derived class object of System.Delegate;
System.object->systemdelegate (iserializable,icloneable)->system.multicastdelegate
->delegate T;
public delegate void Testdelegate (Inti) defines a delegate that internally contains the Invoke method (which is automatically done by the compiler); the invocation of a delegate is actually the invoke method generated when executing the class definition delegate;
Summary: Each delegate contains at least one pointer to the callback method, which can be an instance method or a static method. The mechanism of the delegate implementation callback method is convenient to use;
* The difference between a delegate callback static method and an instance method;
When a delegate binds a static method, the target is null, and the bound instance method is a target that points to an instance object of the type to which the instance method belongs;
* What is a chained delegate: refers to a list of delegates, not another special delegate; Prev, when a delegate is invoked, subsequent delegates of that delegate on all the linked lists are executed sequentially;
* Chain delegate execution order: executes sequentially from the current delegate in the order of the delegate chain. If necessary, the getinvocationlist () can be used to obtain all the delegates that need to be executed on the chain, and execute in any desired order;
* Can define a delegate chain for a method with a return value: a delegate may be a method with a return value, but more than one method to return a value is added to the delegate chain, and the programmer needs to invoke the method on each delegate chain manually;
* Delegated application: The performer of the task assigns the detail work, the performer knows exactly what work is going to be executed, but delegates the execution details to other components, methods or assemblies; some simple key records: (Give an example of multiple modules in an assembly)

2. Events (Event)
Definition: A member that enables an object or class to provide notification, and the client can add executable code for the corresponding event by providing an event handler;
Event Flag __ Delegate type (for example, EventHandler) __ declared events object;
Steps to use the event:
If necessary, define a parameter type derived from System.EventArgs;

Consoleeventargs
Defines the private member of the event in the management type of the event; Consolemanagsder.consoleevent
Notify event subscribers; Consolemanager.sendconsoleevent
Events using a client subscription/unsubscribe event; Log
Supplemental Streamwriter,streamreader, various stream:
using (FileStream fs = File.create (...)) {}
using (StreamWriter SW =info. AppendText ()) {}
* What is the connection between the event and the delegate?
In fact, an event is a delegate type, and when a programmer defines an event, it actually defines a special delegate member. It has no return value, has a fixed two parameter Sender,eventargs, and when the consumer of an event subscribes to an event, the essence is to add the event handling method to the list of delegates; Declaring an event by default adds a pair of add/remove methods for a specific delegate;
* How to design a type with a lot of events? Use EventHandlerList (System.ComponentModel);
Note: Consider thread synchronization measures; Each event defines a set of members-the delegate prototype of the event, the subscription and unsubscribe methods of the event, the type of the event's specific parameters, the reduction of the size of the multi-event type, but the increase in the amount of code;
* In code to indicate the following situation: Cat bark, mouse escape, master awakened <==> cat called by the mouse and the host subscription;

3. Reflection
* The principle of reflection and the cornerstone of its realization: reflection is a mechanism for dynamically analyzing target objects such as assemblies, modules, types, and fields, and its implementation relies on metadata (the cornerstone). Metadata is a block of data stored in a PE file that details the structure within the assembly or module, the reference type, and the assembly manifest. typedef,typeref&assemblyref,assembly;
What types of *.net are available to implement reflection: Assembly,assemblyname,eventinfo,localvariableinfo,manifestresourceinfo,memberinfo,methodbase, Methodbody,module,parameterinfo,propertyinfo;
* How to dynamically launch the assembly: dynamically generate an assembly. Rather than just analyzing the program economy or generating an assembly object, in the System.Reflection.Emit namespace, a series of intermediate codes for dynamic launch assemblies, modules, types, methods, and so on are defined. The main users of these types are compilers, special reflection tools, or script interpreters.
Assemblybuilder,constructorbuilder,customerattributebuilder,enumbuilder,eventbuilder,fieldbuilder, Generictypeparameterbuilder,ilgenerator,localbuilder,methodbuilder,opcodes,parameterbuilder,propertybuilder, TypeBuilder;
Steps:
Define a new assembly in the current AppDomain: AppDomain MyDomain = Thread.getdomain ();
Definition module: assemblybuilder.definedynamicmodule ();
Define the type in the module: Typebuilder addclass=assemblymodule.definetype ();
Define public constructor methods and their parameters type[] Ctorparams = new type[]{typeof (long), typeof (Long)};
Construction Method Intermediate Code ctoril.emit (OPCODES.LDARG_0);
To send an assembly dynamically:
Object Ptinstance=activator.createinstance (Type,ctorparams);
MethodInfo info = type. GetMethod ("GetResult", newtype[0]);//method is obtained by method name and return value type;
The opcodes type contains most of the intermediate code directives that need to be used;
Note: A new assembly launch is a mechanism that directly generates intermediate code in memory rather than generating code on a physical hard disk;
* Using reflection to achieve engineering mode, hands-on;

For each product to do the corresponding attribute, for the product series to do attribute, or need reference
[AttributeUsage (AttributeTargets.Class)]
Public Classproductattribute:attribute
{roompart_myrp = new Roompart ();
Public Productattribute (Roompart RP)
{_myrp = RP; }
Public Roompart Myroompart
{get{return _MYRP;}
} }

[AttributeUsage (Attributetargets.interface)]
Public Classproductlistattribute:attribute
{type[]_mylist;
Public Productlistattribute (type[] productlist)
{_mylist = productlist;}
Public type[] Myproductlist
{get {return _mylist;}}
}
Public iproduct Produce (Roompart RP)
{//through reflection, get properties from IProduct interface to get all product parts list
Productlistattribute pla = (productlistattribute) attribute.getcustomattribute (typeof (IProduct), typeof ( Productlistattribute));
Traverse all of the implementation product part types
foreach (Type type in PLA. Myproductlist) {
Productattribute pa = (productattribute) attribute.getcustomattribute (type,typeof (Productattribute));
if (RP = = Pa. Myroompart) {
Object Pro = Assembly.getexecutingassembly (). CreateInstance (type. FullName);
return Pro as IProduct;
}
return null;}}
* Save Type,field,method information in smaller memory:
Conversion of System.runtimetypehandle and System.Type; Type.gettypehandle (Type), Type.gettypefromhandle (Typehandle);
Conversion of System.runtimemethodhandle and System.Reflection.MethodInfo;
Conversion of System.runtimefeildhandle and System.Reflection.FieldInfo;


4. Features
The feature mechanism helps programmers to programmatically program in a declarative way, rather than having to consider the details of the implementation, a mechanism that resembles the programming concept of AOP;
* What is a feature and how do I customize a feature?
A feature is a programming method that differs from ordinary imperative programming, often referred to as declarative programming. The so-called declarative programming is the programmer order declares that a module will have what kind of characteristics, without concern for implementation; When compiled, unlike traditional imperative code, it is written in binary data to the module file's metadata and is interpreted at runtime. An attribute is also an element that is often applied by the reflection mechanism, because it is stored in the form of meta data itself.
Custom attributes: The essence is to define a type that inherits from the System.Attribute class;
Note: attribute names end with attribute; For convenience, the last attribute can be omitted when using attributes, and other attributes such as [AttributeUsage ()] can be added to the attribute type itself.
*.net attributes can be applied on those elements?
Assembly,module,class,struct,enum,constructor,method,property,field,event,interface,parameter,delegate, Returnvalue,genericparameter;
For elements of type, structure, etc., the use of an attribute can be added above its definition, and for the characteristics of an assembly, module, and so on, it is necessary to show the compiler the purpose of these features, such as: [Assembly:myattribute];
You can use AttributeUsage (AttributeTargets..) To define the scope of use of the feature;
* Get the method that the element has declared attributes:
System.Attribute.IsDefined;
System.Attribute.GetCustomerAttribute ()/getcustomerattributes; finds the specified attribute and its derived attribute. and is instantiated. If the declaration is repeated, the ambiguousmatchexception exception is reported;
System.reflection.customattributedata--getcustomattributes; The use of this type does not result in the instantiation of attributes, which is suitable for systems with high security requirements;
Note: When using these methods, the reader needs to be aware of the need to instantiate the attribute, which means that the byte stream in the metadata will be executed, which may be a security risk. (not understood)
* Can an element declare the same attribute repeatedly? set to true using the AllowMultiple property of AttributeUsageAttribute;

5. The name Enterprise interview real problem
*. What is reflection? A dynamic analysis of assemblies, modules, types, methods, fields and other target object mechanism, it relies on metadata;
*. Under what circumstances has the delegate been used (the answer is not very accurate)? It needs to be used by the user instead of the designer to provide a callback method.
The performer of the task re-assigns the detail task, and the performer knows exactly what work is going to be done, but delegates execution details to other components, methods, or assemblies.
*. Please outline what is the difference between an event and a delegate? The event is a delegate of the specified format, requiring that it has no return value, the parameter is fixed to Object-sender,eventargs-args, and it comes with the Add/remove method, because the callback method is added and removed on the delegate chain ( event handling method);
*. What are your most commonly used features? First, the characteristics of the characteristics: [attributeusage],[serializable] and so on;
*. Describe a custom feature you have designed, why use features?
such as [Target.class]nameattribute, the use of the characteristics of great flexibility, such as the plant design mode optimization, to achieve the role of decoupling, and the characteristics of a declarative way of programming;
*. What is the performance of the reflection mechanism, and under what circumstances will you use reflection? Reflection is a dynamic analysis of the assembly, modules, types, methods, such as the mechanism of the target object, its cornerstone is the metadata; in fact, he is to invoke the method to manipulate the metadata, using it will degrade the performance of the program.
I use it when I need to manipulate target objects such as the temporarily unknown assembly, type, and so on. Because this is a useless method name, field name, and so on. In some special cases, I will also have reflection.emit dynamically create assemblies in memory;
*. What is the function of the dynamic launch code? You can create assemblies directly in memory without residing on the hard disk; it is generally used in compilers, special reflection tools, script interpreters;
*. Please use the code to describe the KFC line to purchase the scene; make a simple version of yourself; Suppose a cashier, come into the queue, buy out of the queue, do not involve multi-threading, algorithm selection and other content;
*. Please describe what the assembly metadata contains? typedef,typeref&assemblyref,assembly list;


Part two:. NET multithreaded Programming
1. The basic concept of multithreaded programming;
* Explain processes and threads at the operating system level
Process: Own program block, exclusive resources and data, and can be called by the operating system;
Thread: is a unit that can be dispatched, and maintains its own stack and context;
In a nutshell, a process represents a running application entity, and a process can contain one or more threads;
The biggest difference between threads and processes is the problem of isolation, where each process is isolated, has its own block of memory, has exclusive resources and runs data, and the interaction between processes is quite difficult. All threads within the same process share resources and memory blocks, and one thread can access and end other threads within the same process;
* Multi-threaded routines are executed in parallel in the OS
Thread scheduling: Preemptive and non-preemptive, such as windows--belonging to both preemptive and non-preemptive modes. For those high priority threads, the use of non-preemption, for ordinary threads, the use of preemptive mode to quickly switch;
On a single CPU architecture, there can only be one running thread at any time, and the OS uses a fast scheduling rotation to make the user feel multithreaded simultaneously. On a multi-CPU architecture, there may be threads running in parallel, depending on whether the resource is competing with the thread, and (Windows presents a hyper-threading concept of virtual CPUs, multi-Channel (Intel)). )
* What is the move? can be regarded as a lightweight thread, with its own stack and context (register) state, scheduling by programmer code control;
Creating a new thread in the. NET Runtime framework does not necessarily guarantee a real thread on the OS level; Think (OS thread, user thread);
In fact, a thread in. NET could be a thread, a move or even a. NET custom structure;
Supplement: The so-called CLR homestay, which refers to the CLR framework running on an application rather than bytes on the operating system. It is common to have asp.net,sqlserver2005.

Multi-threaded programming in 2.net;
* How to manually control multiple threads in. NET; creating a thread-type object does not imply that you are generating one, and you need to call start to generate it;
To control the state of a thread:

* How to use the. NET thread pool;
The so-called. NET thread pool refers to the thread pool managed by the CLR, not the thread pool that is introduced by the. NET Framework; CLR Management Code is responsible for organizing and processing the requirements of the thread, the policy is variable, when the delivery requirements are high, multiple threads may run the processing demand at the same time, instead, only a single thread is created.
Threads running in the thread pool are background threads and IsBackground is true; the so-called background thread means that the running of these threads does not hinder the end of the application;
System.Threading.ThreadPool: Each process has a thread pool,. NET provides a management mechanism, users only need to plug the thread requirements into the pool;
Static Boolqueueuserworkitem (waitcallback--delegate type, accepts the object parameter, no return value--callback)
static bool QueueUserWorkItem (WaitCallback callback, Objectstate)
static bool Unsafequeueuserworkitem (WaitCallback callback, objectstate): Does not pass the main thread permission limit to the worker thread, which may elevate the permissions of the worker thread and create a security vulnerability;
* How to view and set the upper and lower bounds of the thread pool;
Threadpool.get/set max/min/available Threads;
* How to define thread-exclusive global data;
TLS: local thread store; Static variables play a global (AppDomain) visible data role, a static variable that is accessible to the same appDomain thread, and the notion that TLS is required only if the front-thread can access the modified variable;
Mode one, using LocalDataStoreSlot: It is not a thread alone, but initializing an object means allocating a data slot on each thread within the application domain;
LocalDataStoreSlot Ldss =thread. AllocateDataSlot ();
Thread.setdata (Ldss, Thread.CurrentThread.ManagedThreadId);
Thread.getdata (LDSS);
Mode two, ThreadStaticAttribute use
* How to read a file using asynchronous mode;
Asynchronous mode: A pattern that is often used when dealing with stream types, read-write files, network transmissions, read and write databases, and even asynchronous patterns to do any computational work. Asynchronous mode is an efficient programming model relative to the receipt of writing thread code;
When you start an action, you can continue to perform other work without waiting for the end of the operation.
In. NET, many types support asynchronous mode programming, and the following are 4 steps:
Invokes a beginxxx-shaped method that begins an asynchronous execution of an operation;
After calling the BeginXxx method, the main thread can continue to execute arbitrary code without concern for the asynchronous operation condition;
The asynchronous aggregation technique to see the results of an asynchronous operation;
Call EndXxx to represent the result of an asynchronous operation;
The asynchronous pattern differs from the thread pool mechanism:
Call the EndXxx method directly, and if the asynchronous operation is not executed, the main thread is blocked until the one-step operation ends;
View the iscompleted properties of the IAsyncResult object obtained after calling BeginXxx;
The method to be executed at the end of the incoming operation when the beginxxx is called, and the object that executes the asynchronous operation is passed in in order to execute the EndXxx method; (not understood)
Try to use a third technique: the main thread is responsible for starting the asynchronous read and incoming sniper required methods and state objects;
Using (FileStream FS =file.create (_filename))
{String content = @ "Baoshan is a sb, haha!" ";
Byte[] Contentbyte =encoding.default.getbytes (content);
Fs. Write (Contentbyte, 0,contentbyte.length);}
Start reading the contents of the file asynchronously, note that the life cycle of FS here is limited.
using (FileStream fs = new FileStream (_filename, FileMode.Open,FileAccess.Read, FileShare.Read, 1024, fileoptions.asynchronous))
{byte[] data = new byte[1024];
Asyncreadclass arc = new Asyncreadclass (data, FS);
Fs. BeginRead (data, 0, 1024x768, finishread, ARC);
The main thread performs some other operations
Thread.Sleep (1000 * 3);
Console.read ();}
private static void Finishread (Iasyncresultar)
{
Asyncreadclass arc = ar. AsyncState as Asyncreadclass;
To let asynchronous reads occupy the resources released
int length = arc. Fs.endread (AR);//Notice the life cycle of the object}

* How to prevent thread execution context delivery;
The threads in the same process share resources and memory blocks, but still have their own on-line ask, in. NET, the context of the thread has a flow characteristic;
The contents of the thread execution context: The security context, the invocation context, the synchronization context, the localization context, the transaction context, and the CLR host context;
Context Flow: Thread Thread;thread. Start (); Thread.Join ()//block current thread;
How to block the flow of context: the context in which the thread executes is a wrapper for all threads, and in general, the execution context of the current thread flows into the new thread. Programmers can use the Unsafequeueuserworkitem method defined in the System.Threading.ThreadPool type and the Suppressflow method defined in the ExecutionContext type to prevent this flow. Note that this can improve efficiency, but will reduce security;

3. Thread synchronization for multi-threaded threads
* What is fast and synchronous fast index;
The. NET team has considered thread synchronization when designing the basic framework, using a compromise approach: assigning an index to each memory object that only has an integer that indicates an index within the array. A new synchronization block array is created at. NET load, and when an object needs to be synchronized,. NET assigns it a synchronization block and adds the synchronization block's index in the synchronized array to the synchronization block index of the object;
When a thread attempts to use the object to enter synchronization, it checks the synchronization index of the object, and if the index is negative, looks for or creates a new synchronization block in the synchronized Block array, places the synchronization block index value in the object's synchronization block index, finds the synchronization block if it is not negative, and checks if it is used by another thread. If there is a wait state, declare the synchronization block if it doesn't work.
Enter and exit Sync: system.threading.monitor.enter/exit;
What does the lock keyword in *c# do;
Lock is equivalent to monitor.entry/exit; In general, lock a private reference member variable to complete the thread synchronization of the member method, using a private static reference variable to complete the thread synchronization of the static method;
* Can I use a value type object to implement thread synchronization? No, there will be a serious error, monitor related methods will be used when the disassembly box, each time the objects in the heap will change, a serious error occurred. Instead of using Monitor.entrr/exit, lock should be used;
* Can synchronize the reference type itself; Yes, but such a program lacks robustness (lock (this), Lock (Typeof (...)) ), when a type consumer maliciously consumes the object's synchronization block for a long time, all other objects are deadlocked;
* What is the difference between what is a mutex, the type of mutex, and the function of the monitor type (WaitHandle (abstract base class for all encapsulated Kernel synchronization objects), similar to Semaphone,eventwaithandler);
Mutex.waitone (); Mutex.close (); Mutex.releasemutex ();
The mutex uses the OS kernel object, and monitor is implemented in the. NET Framework, and the mutex is inefficient (10 times times, user-state, System State);
Monitor can synchronize only one thread in a Appdomian, while a mutex can span a process;
4. The real problem of famous enterprises;
* How do processes and threads understand? The process in the operating system has its own independent memory space (including blocks, blocks), such as Win32 (allocating 4G of virtual memory space), the process can be dispatched by the operating system, simply speaking, a process represents a running application entity, Can contain one or more threads; a thread is a unit that can be dispatched to maintain its own stack and context;
The maximum difference between a process and a thread is isolation, where each process runs independently, has its own block of memory, has exclusive resources, and has difficulty interacting with one another, while multiple threads in a process can share data and memory blocks, one thread can access, and another thread in the same process ends;
* Based on the knowledge of thread safety, analyze whether i>10 will cause deadlocks when test is called:
public void Test (int i) {
Lock (This) {
if (i>10) {
i--;
Test (i);
}}}//first does not recommend the use of this lock mode;//not deadlock, because the value type is passed; (Not OK)
* What is the difference between a background thread and a normal thread:
The foreground thread can block the end of the application until all foreground threads have terminated before the CLR shuts down the application. The background thread, also known as the daemon thread, is considered by the CLR to be a way to make sacrifices in program execution, that is, it can be ignored at any time, so if all the foreground threads are terminated, all background threads will be automatically terminated when the application unloads.
* There are several ways to share data between multiple threads? (here the sharing is actually refers to how to synchronize) Lock,mutex;
* The difference between lock and mutex: The lock is much higher in efficiency, but because the mutex is the OS kernel object, the synchronization between multiple processes can be realized.
* Can I use lock on a value type? No, the mechanism of the CLR is to allocate a synchronous block index in all heap objects, with no value type;
* When will you consider using multithreading? For example, considering the corresponding speed, do not want to be affected by the blocking of the resource users;
* Does a new thread using the thread type come from the thread pool? must not, Threadpool.queueuseworkitem ();

Part III. NET UNIT tests
1. Basic concepts of unit testing;
* Briefly describe the concept and advantages of unit testing;
* Examples of TDD development process;
* Programming factorial function module test case;

2. Use NUnit for unit testing;
* How to use NUnit for unit testing;
* How to classify the test cases;
* Explaining Setup,teardown;

3. The name Enterprise interview real problem;

. NET work Preparation--03 advanced knowledge

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.