improve watchespn quality

Want to know improve watchespn quality? we have a huge selection of improve watchespn quality information on alibabacloud.com

157 recommendations for writing high-quality code to improve C # programs--Recommendation 105: Using private constructors to harden a single case

Singleton is: Public Sealed classSingleton {StaticSingleton instance =NULL; Static ReadOnly Objectpadlock=New Object(); //restrict instances from being created externally PrivateSingleton () {} Public StaticSingleton Instance {Get { if(Instance = =NULL) { Lock(padlock) {if(Instance = =NULL) {instance=NewSingleton (); } } } returninstance; } } Public voidSampleMe

157 recommendations for writing high-quality code to improve C # programs--Recommendation 59: Don't throw exceptions in inappropriate situations

the friendly information.Situation ThreeIf the underlying exception does not make sense in the context of a high-level operation, consider capturing these underlying exceptions and throwing new meaningful exceptions. If a invalidcastexception is raised as a new ArgumentException.A typical example of a properly thrown exception is capturing the underlying API error code and throwing it. Looking at the console class, you'll also find a lot of places with similar code: int errorCode = m

157 recommendations for writing high-quality code to improve C # programs--Recommendation 104: Replacing conditional statements with polymorphism

{ publicabstractvoid Execute (); }All commands such as start or stop are inherited from this abstract class: class Startcommander:commander { publicoverridevoid Execute () { // start } } class Stopcommander:commander { public overridevoid Execute () { // stop } }After using polymorphism, the code that invokes the method should look like this: Static void Main (string[] args) {

157 recommendations for writing high-quality code to improve C # programs--Recommendation 103: Differentiating combinations and inheritance applications

other types. If you combine too many types, it means that the current class is likely to do too many things, and it needs to be split into two classes. Inheritance does not have such an attribute, in C #, a subclass can have only one base class (the interface releases this restriction, and subclasses inherit from multiple interfaces).The use of inheritance or composition should be considered according to the actual situation. In general, the combination can be more satisfying for most applicati

157 recommendations for writing high-quality code to improve C # programs--recommendation 88: Parallelism is not always faster

synchronization took only 0.55 milliseconds, while parallelism used 3.3 milliseconds to complete the work.Now, to simulate getting the loop body to do more, change the loop body in the DoSomething method from 10 to 10000000. The result of the operation is:Synchronization time: 00:00:01.3059138Concurrent Time: 00:00:00.6560593When the loop body needs to do more work, we find that synchronization takes 1.3 seconds to complete the work, while in parallel the work is done in only 0.6 seconds.Turn f

157 recommendations for writing high-quality code to improve C # programs--Recommendation 35: Use default to specify initial values for generic type variables

Recommendation 35: Use default to specify an initial value for a generic type variableSome algorithms, such as the Find algorithm for generic collection list Public T func() { null; return t; }Cannot convert null to type parameter ' T ' because it may be a non-nullable value type. Consider using "Default (T)" instead. Public T func() { 0; return t; }The type "int" cannot be implicitly converted to "T".So the above code

157 recommendations for writing high-quality code to improve C # programs--Recommendation 55: Reduce serializable fields with custom features

{//serializing a type to a string Public Static stringSerialize(T t) {using(MemoryStream stream =NewMemoryStream ()) {BinaryFormatter Formatter=NewBinaryFormatter (); Formatter. Serialize (stream, T); returnSystem.Text.Encoding.UTF8.GetString (stream. ToArray ()); } } //serializing a type to a file Public Static voidSerializetofilestringPathstringfullName) { if(!directory.exists (path)) {directory.createdirectory (pat

157 recommendations for writing high-quality code to improve C # programs--Recommendation 33: Avoid declaring static members in generic types

as much as possible during the actual coding process.A static generic method in a non-generic type looks close to the example, but a generic method in a non-generic style does not generate a different type in the local code at run time.As follows: classMyList {Static intcount; Public Static intFunc() { returncount++; } } Static voidMain (string[] args) {Console.WriteLine (Mylist.funcint>()); Console.WriteLine (Mylist.funcint>()); Console.WriteLine

157 recommendations for writing high-quality code to improve C # programs--Recommendation 83: Beware of traps in parallel

if two threads are used, the output is 12 according to the logic of the program.In this code, if you let Localinit return a value of 0, you might never notice the trap:() = { return0; Now, to understand this trap more clearly, let's use this better-understood code:Static voidMain (string[] args) { string[] Stringarr =New string[] {"AA","BB","cc","DD","ee","FF", "GG","hh" }; stringresult =string. Empty; Parallel.Forstring> (0, Stringarr.length, () ="-", (i, Lo

157 recommendations for writing high-quality code to improve C # programs--Recommendation 81: Use parallel to simplify task usage in a synchronous state

traversal is parallel, not sequential. So, here's a tip: if our output has to be synchronous or must be sequential, then parallel should not be used.The Foreach method is primarily used to handle parallel operations of generic collection elements, as follows: static void Main (string [] args) {List int > nums = new listint > {1 , 2 , 3 , 4 }; Parallel.ForEach (Nums, (item) => {Console.WriteLine ( " Some work code for collection element {0} ... " The output is:Some wor

157 recommendations for writing high-quality code to improve C # programs--recommendation 80: Replace ThreadPool with Task

); Console.readkey (); Cts. Cancel (); Console.readkey (); } Static voidtasksended (task[] tasks) {Console.WriteLine ("All tasks are complete! "); } The output of the above code is:Task begins ...Task begins ...Task begins ...All tasks have been completed (canceled)!This recommendation shows how task (Task) and TaskFactory (Task Factory) are used. Task further optimizes the scheduling of the background thread pool and speeds up the processing of threads. So in the FCL 4.0 era, if yo

157 recommendations for writing high-quality code to improve C # programs-Recommendation 69: Use finally to avoid resource leaks

=NewClassshoulddisposebase ("Method1"); METHOD2 (); } finally{c.dispose (); } } Static voidMethod2 () {classshoulddisposebase C=NULL; Try{C=NewClassshoulddisposebase ("Method2"); } finally{c.dispose (); } }Output:In method: Method2 is released!In method: Method1 is released!Finally does not terminate because of an exception that exists in the call stack, and the CLR executes the catch block before executing the finally block. As follows:

157 recommendations for writing high-quality code to improve C # programs--Recommendation 67: Use custom exceptions with caution

) { thrownew dataaccessexception (); } }The same is true for SQLite's data access layer. The business layer code at the beginning of this article can be changed to: Iuserdal dal = dataaccess.createuserdal (); Try { = dal. Getoneuser (); } Catch (DataAccessException ex) { // Handling Data connection exception }Turn from: 157 recommendations for

157 recommendations for writing high-quality code to improve C # programs--Recommendation 31: Avoid unnecessary iterations in LINQ queries

searching for a second element that satisfies the condition and returning from the collection. If a collection contains a lot of elements, this kind of query can bring us considerable time efficiency.Like the first method, the take method receives an integer parameter, and then we return the number specified by the parameter. As with first, it returns directly from the current iteration, rather than waiting for the entire iteration to complete before it satisfies the condition. If a collection

157 recommendations for writing high-quality code to improve C # programs--Recommendation 51: Types with disposable fields or types that own native resources should be disposable

; }} disposed=true; } Public voidSamplepublicmethod () {if(disposed) {Throw NewObjectDisposedException ("Anothersampleclass","Anothersampleclass is disposed"); } //omitted } }Type Anothersampleclass Although it does not contain any explicit unmanaged resources, because it contains a non-trivial type, we still have to implement a standard dispose pattern for it.In addition, a type has a native resource (that is, an unmanaged resource) and it should inherit the IDispos

157 recommendations for writing high-quality code to improve C # programs--Recommendation 26: Using anonymous types to store LINQ query results

to assign values directlyListNewList() { NewPerson () {Name ="Mike", CompanyID =1 }, NewPerson () {Name ="Rose", CompanyID =0 }, NewPerson () {Name ="Steve", CompanyID =1 } }; varPersonwithcompanylist = fromPersoninchPersonlist Join Companyinchcompanylist on Person.companyid equals Company.comanyidSelect New{personname = person. Name, CompanyName =Company . Name}; foreach(varIteminchpersonwithcompanylist) {Console.Wri

157 recommendations for writing high-quality code to improve C # programs--Recommendation 73: Avoid locking inappropriate synchronization objects

types (such as ArrayList) provided public property syncroot, which allowed us to lock in for some thread-safe operation. So you will feel that we have just concluded that it is not correct. In fact, most of the ArrayList operations do not involve multi-threaded synchronization, so its approach is more of a single-threaded application scenario. Thread synchronization is a very time-consuming (inefficient) operation. If all non-static methods of ArrayList are considered thread-safe, then ArrayLis

157 recommendations for writing high-quality code to improve C # programs--Recommendation 15: Use dynamic to simplify reflection implementation

)); Dynamic Dynamicsample=Newdynamicsample (); Stopwatch WATCH2=stopwatch.startnew (); for(inti =0; I ) {Dynamicsample.add (1,2); } Console.WriteLine (string. Format ("Dynamic time: {0} milliseconds", Watch2. Elapsedmilliseconds)); The output is:Reflection Time: 2575 msDynamic Time: 76 msAs can be seen, there is no optimized reflection implementation, the above loop execution efficiency is much lower than the performance of the dynamic implementation. If the reflection implementation is optimiz

157 recommendations for writing high-quality code to improve C # programs--recommendation 24: iterators should be read-only

iterations to the UI: Private New MyList (); Private Imyenumerator enumerator = list. GetEnumerator (); while (Enumerator. MoveNext ()) { int current = Enumerator. Current; Console.WriteLine (current. ToString ()); }Business Class B to implement a new iterator for the collection object, for one of its own needs: Private New as MyList); as MyList). Setenumerator (Enumerator2); while (Enumerator2. MoveNext ())

157 recommendations for writing high-quality code to improve C # programs--recommendation 63: Avoid "eating" exceptions

heartbeat data to determine the online situation on the controlled side. The usual practice is to maintain a model quantity, if in an acceptable block time (such as 500ms) heartbeat data transmission failure, then the control thread will not receive a signal, that is, can judge the short-term status of the controlled side. In this case, it is usually meaningless to record each socketexception.If you do not know how to handle an exception, then do not "eat" the exception, if you accidentally "ea

Total Pages: 9 1 .... 5 6 7 8 9 Go to: Go

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.