C# 예외 개선

PHPz
풀어 주다: 2017-03-12 15:45:50
원래의
1180명이 탐색했습니다.

0. 카탈로그

C#6 기능 디렉토리

1. catch 및 최종 블록 사용 wait

는 새로운 비동기 프로그래밍 모델 을 지원하기 위해 C#5에 한 쌍의 키워드 wait/async를 도입하여 C# 비동기 프로그래밍 모델을 더욱 단순화합니다(APM ->EAP->TAP->await/async. C#의 비동기 프로그래밍 모델은 이 기사의 소개 초점이 아닙니다. 자세한 내용은 여기 Asynchr유일한 프로그래밍 패턴). Wait/async는 C#5에 도입되었지만 몇 가지 제한 사항이 있습니다. 예를 들어 catch 및 finally 문 블록에서는 이 제한 사항이 더 이상 적용되지 않습니다.


 1 using System; 2 using System.Threading; 3 using System.Threading.Tasks; 4  5 namespace csharp6 6 { 7     internal class Program 8     { 9         private static void Main(string[] args)10         {11             do12             {13                 Log(ConsoleColor.White, "caller method begin", true);14                 CallerMethod();15                 Log(ConsoleColor.White, "caller method end");16             } while (Console.ReadKey().Key != ConsoleKey.Q);17         }18 19         public static async void CallerMethod()20         {21             try22             {23                 Log(ConsoleColor.Yellow, "try ", true);24                 throw new Exception();25             }26             catch (Exception)27             {28                 Log(ConsoleColor.Red, "catch await begin", true);29                 await AsyncMethod();30                 Log(ConsoleColor.Red, "catch await end");31             }32             finally33             {34                 Log(ConsoleColor.Blue, "finally await begin", true);35                 await AsyncMethod();36                 Log(ConsoleColor.Blue, "finally await end");37             }38         }39 40         private static Task AsyncMethod()41         {42             return Task.Factory.StartNew(() =>43             {44                 Log(ConsoleColor.Green, "async method begin");45                 Thread.Sleep(1000);46                 Log(ConsoleColor.Green, "async method end");47             });48         }49 50         private static void Log(ConsoleColor color, string message, bool newLine = false)51         {52             if (newLine)53             {54                 Console.WriteLine();55             }56             Console.ForegroundColor = color;57             Console.WriteLine($"{message,-20} : {Thread.CurrentThread.ManagedThreadId}");58         }59     }60 }
로그인 후 복사
실행 결과는 다음과 같습니다.

조심하면

비동기 방식을 찾을 수 있습니다. Begin:6이 줄의 색상은 제가 설정한 녹색이 아니고 흰색이고 순서도 어긋나서 다시 실행하면 녹색이 될 수도 있습니다. 이는 실제로 여러 스레드에서 호출되는 Log 메서드(스레드가 아닌 안전한 메서드)의 두 줄의 코드로 인해 발생합니다.


1 Console.ForegroundColor = color;2 Console.WriteLine($"{message,-20} : {Thread.CurrentThread.ManagedThreadId}");
로그인 후 복사
우리는 Log 메서드를 스레드로부터 안전하게 만들기 위해 몇 가지 작은 변경을 할 수 있습니다(C#에서는 여러 가지 방법이 있지만 이는 그 중 하나일 뿐입니다).


 1 [MethodImpl(MethodImplOptions.Synchronized)] 2 private static void Log(ConsoleColor color, string message, bool newLine = false) 3 { 4     if (newLine) 5     { 6         Console.WriteLine(); 7     } 8     Console.ForegroundColor = color; 9     Console.WriteLine($"{message,-20} : {Thread.CurrentThread.ManagedThreadId}");10 }
로그인 후 복사
주제에서 조금 벗어난 주제로 돌아가서, catch 및 finally 문 블록에서 wait 키워드를 지원하려면 IL 명령이나 CLR 지원이 필요하지 않으며 단지 컴파일러에서 수행한 코드 변환입니다(await /async는 위임할 람다와 같습니다. 특정 IL에 대해 확장하지는 않겠습니다. 다음 그림은 일반적인 상황을 보여줍니다.

CallerMethod에서 작성한 코드가 Move 다음

(자세한 내용은 정원 친구 "Dev_Eric"의 블로그를 방문하세요. 고급: IL을 검으로 사용하여 async/await를 직접 가리킴)(catch 및 finally의 wait 문 포함). 2. 예외

필터

사실 이 언어 기능은 오랫동안 VB와 F#에서 지원됐는데 이제는 C#에서도 사용할 수 있습니다. 6.

1 try { … }2 catch (Exception e) when (filter(e))3 {4     …5 }
로그인 후 복사

When 섹션은 표현식

이 뒤에 오는 부분입니다. catch 문 블록. 3. 참조

비동기 프로그래밍 패턴

c# 6.0 wait in catch/finally

C# 6.0 예외 필터

http:/ / /www.php.cn/

위 내용은 C# 예외 개선의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
c#
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!