[C#6] 8-Exception enhancement

Source: Internet
Author: User

0. Catalogue

C#6 new features Directory

1. Using await in catch and finally blocks

A pair of keyword Await/async was introduced in c#5 to support the new asynchronous programming model, making the C # asynchronous programming model further simplified (apm->eap->tap->await/async, about C # The asynchronous programming model in this article is not the focus of the introduction, detailed information please visit here Asynchronous Programming Pattern). Although Await/async is introduced in c#5, there are some limitations, such as the inability to use catch and finally statement blocks, which are no longer restricted in c#6.

1 usingSystem;2 usingSystem.Threading;3 usingSystem.Threading.Tasks;4 5 namespaceCSHARP66 {7     Internal class Program8     {9         Private Static voidMain (string[] args)Ten         { One              Do A             { -Log (Consolecolor.white,"Caller method Begin",true); - Callermethod (); theLog (Consolecolor.white,"Caller method End"); -} while(Console.readkey (). Key! =consolekey.q); -         } -  +          Public Static Async voidCallermethod () -         { +             Try A             { atLog (Consolecolor.yellow,"Try",true); -                 Throw NewException (); -             } -             Catch(Exception) -             { -Log (consolecolor.red,"catch await begin",true); in                 awaitAsyncmethod (); -Log (consolecolor.red,"catch await end"); to             } +             finally -             { theLog (Consolecolor.blue,"finally await begin",true); *                 awaitAsyncmethod (); $Log (Consolecolor.blue,"finally await end");Panax Notoginseng             } -         } the  +         Private StaticTask Asyncmethod () A         { the             returnTask.Factory.StartNew (() = +             { -Log (Consolecolor.green,"Async Method Begin"); $Thread.Sleep ( +); $Log (Consolecolor.green,"Async Method End"); -             }); -         } the  -         Private Static voidLog (Consolecolor color,stringMessageBOOLNewLine =false)Wuyi         { the             if(NewLine) -             { Wu Console.WriteLine (); -             } AboutConsole.foregroundcolor =color; $Console.WriteLine ($"{message,-20}: {Thread.CurrentThread.ManagedThreadId}"); -         } -     } -}

The results of the operation are as follows:

If you are careful you will find that async method Begin:6 The color of this line is not I set the green, but white, and the order is also a disorder, and you run it again, it may be green. This is due to the fact that I have two lines of code in the Log method (non-thread-safe method) being scrambled by multiple threads:

1 console.foregroundcolor = color; 2 Console.WriteLine ($"{message,-20}: {Thread.CurrentThread.ManagedThreadId}" );

We can make a little change to make the log method thread safe (there are many ways to do this in C #, which is just one of them):

1 [MethodImpl (methodimploptions.synchronized)]2 Private Static voidLog (Consolecolor color,stringMessageBOOLNewLine =false)3 {4     if(NewLine)5     {6 Console.WriteLine ();7     }8Console.foregroundcolor =color;9Console.WriteLine ($"{message,-20}: {Thread.CurrentThread.ManagedThreadId}");Ten}

Seems a little off-topic, back to the point, support for the await keyword in catch and finally statement blocks does not require the support of the IL directive, nor does it require the support of the CLR, but is simply a compiler-made code conversion (await/ Async is like a lambda to delegate). The specific IL will not do the expansion, too large, put a picture to see the general situation:

We wrote in the Callermethod code, was transferred to the MoveNext (more detailed information please visit the Garden Friends "Dev_eric" a blog: Advanced article: With Il as the sword, pointing to async/ await) (includes the catch and the await statement in finally).

2. Exception filter

In fact, the language features in the vb,f# has long been supported, and now c#6 inside can also be used.

1 Try {...} 2 Catch (Exception E) When (filter (e)) 3 {4    ... 5 }

Where when this piece is where the exception filter is in effect, when followed by an expression, the expression results if true, then enter the current catch statement block.

3. Reference

Asynchronous Programming Patterns

C # 6.0 await in catch/finally

C # 6.0 Exception filters

Http://www.sadev.co.za/content/exception-filtering-c-6

[C#6] 8-Exception enhancement

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.