Microsoft MVP성태의 닷넷 이야기
닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [링크 복사], [링크+제목 복사],
조회: 10679
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

async 메서드 내에서 C# 7의 discard 구문 활용 사례

async 메서드 내에서 보통 Task를 반환하는 메서드에 대해서는 await 호출을 하게 됩니다.

namespace ConsoleApp1;

internal class Program
{
    static async Task Main(string[] args)
    {
        await TaskWait();
    }

    private static Task TaskWait()
    {
        return Task.Run(() =>
        {
            Thread.Sleep(500);
            Console.WriteLine("Hello World!");
        });
    }
}

그런데, 사실 어떤 경우에는 await 없이 호출하고 싶을 수도 있습니다. 예를 들어, Log를 await 없이 수행하고 싶을 수 있는데요, 이럴 때 스레드 풀을 사용하도록 Task.Run을 사용할 수도 있습니다.

namespace ConsoleApp1;

internal class Program
{
    static async Task Main(string[] args)
    {
        Task.Run(() =>
        {
            Console.WriteLine("Hello World!");
        });

        await Task.Delay(500);
    }
}

문제는, 저 코드가 컴파일은 되지만, 경고가 발생한다는 점입니다.

await_warn_1.png

warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.


그냥 봐도 눈에 거슬립니다. ^^ 이 경고를 없애려면 Task.Run을 사용하지 않고 Thread나 ThreadPool.QueueUserWorkItem을 이용하면 됩니다.

static async Task Main(string[] args)
{
    Thread t = new Thread(() =>
    {
        Console.WriteLine("Hello World!");
    });
    t.Start();

    await Task.Delay(500);
}




만약 Task.Run을 고집하고 싶다면 어떻게 해야 할까요? 이런 경우, 경고를 해당 구간 내에서만 비활성 상태로 둘 수 있습니다.

static async Task Main(string[] args)
{
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
    Task.Run(() =>
    {
        Console.WriteLine("Hello World!");
    });
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

    await Task.Delay(500);
}

하지만 보는 바와 같이 소스코드가 좀 지저분해지는 문제가 있습니다. 혹은 그냥 Task 변수를 하나 받는 것도 방법입니다.

static async Task Main(string[] args)
{
    var task = Task.Run(() =>
    {
        Console.WriteLine("Hello World!");
    });

    await Task.Delay(500);
}

이렇게 되면 경고는 없어지지만 쓸데없는 변수 하나 있는 게 좀 거슬립니다. 다행히, 이에 대한 보다 더 나은 선택지가 있습니다. ^^

warning this call is not awaited, execution of the current method continues
; https://stackoverflow.com/questions/14903887/warning-this-call-is-not-awaited-execution-of-the-current-method-continues

다름 아닌 C# 7에 추가되었던 discard 구문을 바로 task 변수를 없애는 목적으로도 사용할 수 있는 것입니다. 이렇게!

static async Task Main(string[] args)
{
    _ = Task.Run(() =>
    {
        Console.WriteLine("Hello World!");
    });

    await Task.Delay(500);
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 1/6/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2024-01-22 10시47분
👍 좋아요 기능이 시급합니다ㅎ
al6uiz

... 166  167  168  169  170  171  172  173  174  175  176  177  [178]  179  180  ...
NoWriterDateCnt.TitleFile(s)
587정성태6/10/200828650VS.NET IDE: 56. C#에서 아쉬운 __DATE__, __TIME__ 매크로 [2]
586정성태6/4/200826270오류 유형: 56. WPF 디자이너 - The string was not recognized as a valid DateTime [2]
585정성태6/4/200834574.NET Framework: 101. WPF - ActiveX 컨트롤 호스팅하는 방법 [2]
582정성태5/16/200826343오류 유형: 55. Windowless ActiveX controls are not supported
580정성태4/24/200825415VC++: 34. 64비트 윈도우즈에서의 이벤트 후킹
579정성태4/24/200825233VC++: 33. 변환 후의 RGS 파일 내용을 얻는 방법
577정성태4/16/200826164.NET Framework: 100. XML Serializer를 이용한 값 복사 [5]
575정성태4/7/200823335오류 유형: 54. TFS Source Control - 명령을 사용할 수 없음 [2]
574정성태3/31/200821451오류 유형: 53. TFS 연결 오류 - The workspace [...] exists on computer [...]
573정성태3/25/200825478Windows: 31. TS Web Access와 UAC [1]
570정성태3/17/200824628오류 유형: 52. TFS 연결 오류 - TF31001 [2]
569정성태3/16/200825769Team Foundation Server: 24. TFS 2008로 마이그레이션 (2) [2]
566정성태2/28/200826907.NET Framework: 99. AppDomain.GetEntryAssembly()를 우회하는 방법파일 다운로드1
564정성태2/16/200826545Windows: 30. TS Web Access + Vista SP1 [2]
563정성태2/16/200825911오류 유형: 51. Vista(UAC) + 웹 프로젝트 디버깅: System.UnauthorizedAccessException
562정성태2/12/200830174Windows: 29. Windows Server 2008 설치 [4]
561정성태1/10/200823865오류 유형: 50. IE 7 + 잘못된 HTC 파일 경로 = File not found [5]
559정성태1/1/200828680Windows: 28. Vista에서 끌어다 놓기로 GAC 등록하는 방법 [2]
558정성태1/1/200845869개발 환경 구성: 33. 32bit/64bit OLE DB Provider [1]
557정성태12/22/200724208개발 환경 구성: 32. WSCF와 VS.NET 2008
556정성태12/16/200722282기타: 22. 인기 순위 정리 : 조회수 1000 회 이상
555정성태12/16/200725263기타: 21. 인기 순위 정리 : 조회수 500 ~ 999회 글 목록
554정성태12/16/200729654기타: 20. 인기 순위 정리 : 조회수 250 ~ 499회 글 목록
553정성태12/16/200730039기타: 19. 인기 순위 정리 : 조회수 100 ~ 249회 글 목록
552정성태12/16/200723646기타: 18. 인기 순위 정리 : 조회수 000 ~ 099 회 글 목록
550정성태12/16/200722859Team Foundation Server: 23. TFS 2005에서 TFS 2008로 마이그레이션 [2]
... 166  167  168  169  170  171  172  173  174  175  176  177  [178]  179  180  ...