수색…


통사론

  • 비동기 및 대기

  • 공용 작업 MyTask Async () {doSomething (); }

    MyTaskAsync ()를 기다린다.

  • 공용 작업 <string> MyStringTask Async () {return getSomeString (); }

    string MyString = MyStringTaskAsync ()를 기다립니다.

  • 발신자 정보 속성

  • 공공 무효 MyCallerAttributes (문자열 MyMessage,

    [CallerMemberName] 문자열 MemberName = "",

    [CallerFilePath] string SourceFilePath = "",

    [CallerLineNumber] int LineNumber = 0)

  • Trace.WriteLine ( "내 메시지 :"+ MyMessage);

    Trace.WriteLine ( "Member :"+ MemberName);

    Trace.WriteLine ( "원본 파일 경로 :"+ SourceFilePath);

    Trace.WriteLine ( "Line Number :"+ LineNumber);

매개 변수

매개 변수가있는 메서드 / 한정자 세부
Type<T> T 는 반환 유형입니다.

비고

C # 5.0은 Visual Studio .NET 2012와 결합됩니다.

비동기 및 대기

asyncawait 는 스레드를 해제하고 작업이 완료 될 때까지 기다렸다가 성능을 향상시키려는 두 가지 연산자입니다.

다음은 길이를 반환하기 전에 문자열을 가져 오는 예제입니다.

//This method is async because:
//1. It has async and Task or Task<T> as modifiers
//2. It ends in "Async"
async Task<int> GetStringLengthAsync(string URL){
    HttpClient client = new HttpClient();
    //Sends a GET request and returns the response body as a string
    Task<string> getString = client.GetStringAsync(URL);
    //Waits for getString to complete before returning its length
    string contents = await getString;
    return contents.Length;
}

private async void doProcess(){
    int length = await GetStringLengthAsync("http://example.com/");
    //Waits for all the above to finish before printing the number
    Console.WriteLine(length);
}

다음은 파일을 다운로드하고 진행 상황이 변경되고 다운로드가 완료되면 어떻게되는지 처리하는 다른 예입니다 (두 가지 방법이 있습니다).

방법 1 :

//This one using async event handlers, but not async coupled with await
private void DownloadAndUpdateAsync(string uri, string DownloadLocation){
    WebClient web = new WebClient();
    //Assign the event handler
    web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
    web.DownloadFileCompleted += new AsyncCompletedEventHandler(FileCompleted);
    //Download the file asynchronously
    web.DownloadFileAsync(new Uri(uri), DownloadLocation);
}

//event called for when download progress has changed
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e){
    //example code
    int i = 0;
    i++;
    doSomething();
}

//event called for when download has finished
private void FileCompleted(object sender, AsyncCompletedEventArgs e){
    Console.WriteLine("Completed!")
}

방법 2 :

//however, this one does
//Refer to first example on why this method is async
private void DownloadAndUpdateAsync(string uri, string DownloadLocation){
    WebClient web = new WebClient();
    //Assign the event handler
    web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
    //Download the file async
    web.DownloadFileAsync(new Uri(uri), DownloadLocation);
    //Notice how there is no complete event, instead we're using techniques from the first example
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e){
    int i = 0;
    i++;
    doSomething();
}
private void doProcess(){
    //Wait for the download to finish
    await DownloadAndUpdateAsync(new Uri("http://example.com/file"))
    doSomething();
}

발신자 정보 속성

CIA는 대상 메서드를 호출하는 모든 요소에서 특성을 가져 오는 간단한 방법입니다. 실제로 사용하는 방법은 단 하나 뿐이며 3 가지 속성 만 있습니다.

예:

//This is the "calling method": the method that is calling the target method
public void doProcess()
{
    GetMessageCallerAttributes("Show my attributes.");
}
//This is the target method
//There are only 3 caller attributes
public void GetMessageCallerAttributes(string message,
    //gets the name of what is calling this method
    [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
    //gets the path of the file in which the "calling method" is in
    [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
    //gets the line number of the "calling method"
    [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    //Writes lines of all the attributes
    System.Diagnostics.Trace.WriteLine("Message: " + message);
    System.Diagnostics.Trace.WriteLine("Member: " + memberName);
    System.Diagnostics.Trace.WriteLine("Source File Path: " + sourceFilePath);
    System.Diagnostics.Trace.WriteLine("Line Number: " + sourceLineNumber);
}

출력 예 :

//Message: Show my attributes.
//Member: doProcess
//Source File Path: c:\Path\To\The\File
//Line Number: 13


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow