Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

(시리즈 글이 14개 있습니다.)
.NET Framework: 698. C# 컴파일러 대신 직접 구현하는 비동기(async/await) 코드
; https://www.sysnet.pe.kr/2/0/11351

.NET Framework: 716. async 메서드의 void 반환 타입 사용에 대하여
; https://www.sysnet.pe.kr/2/0/11414

.NET Framework: 717. Task를 포함하지 않는 async 메서드의 동작 방식
; https://www.sysnet.pe.kr/2/0/11415

.NET Framework: 719. Task를 포함하는 async 메서드의 동작 방식
; https://www.sysnet.pe.kr/2/0/11417

.NET Framework: 731. C# - await을 Task 타입이 아닌 사용자 정의 타입에 적용하는 방법
; https://www.sysnet.pe.kr/2/0/11456

.NET Framework: 737. C# - async를 Task 타입이 아닌 사용자 정의 타입에 적용하는 방법
; https://www.sysnet.pe.kr/2/0/11484

.NET Framework: 813. C# async 메서드에서 out/ref/in 유형의 인자를 사용하지 못하는 이유
; https://www.sysnet.pe.kr/2/0/11850

.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리
; https://www.sysnet.pe.kr/2/0/12838

닷넷: 2138. C# - async 메서드 호출 원칙
; https://www.sysnet.pe.kr/2/0/13405

닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
; https://www.sysnet.pe.kr/2/0/13421

닷넷: 2318. C# - (async Task가 아닌) async void 사용 시의 부작용
; https://www.sysnet.pe.kr/2/0/13884

닷넷: 2319. ASP.NET Core Web API / Razor 페이지에서 발생할 수 있는 async void 메서드의 부작용
; https://www.sysnet.pe.kr/2/0/13885

닷넷: 2321. Blazor에서 발생할 수 있는 async void 메서드의 부작용
; https://www.sysnet.pe.kr/2/0/13888

닷넷: 2335. C# - 간단하게 구현해 보는 IValueTaskSource 예제
; https://www.sysnet.pe.kr/2/0/13950




ASP.NET Core Web API / Razor 페이지에서 발생할 수 있는 async void 메서드의 부작용

지난 글에서 async void 메서드의 부작용을 설명했었는데요,

C# - (async Task가 아닌) async void 사용 시의 부작용
; https://www.sysnet.pe.kr/2/0/13884

이런 문제가 ASP.NET Core Web Application 기반의 Web API나 Razor 페이지에서 발생할 수 있습니다. 하나씩 예를 들어 볼까요? ^^

가령, Web API 프로젝트를 생성한 경우 기본 제공되는 WeatherForecastController는,

using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

Get 메서드가 동기 함수인데요, 다행히 이런 경우에는 (반드시 값을 반환해야 하기 때문에) async void로 작성하는 실수를 할 여지가 없습니다.

public async IEnumerable<WeatherForecast> Get()

[내부에서 await 호출을 하고 싶다면]
==> public async Task<IEnumerable<WeatherForecast>> Get()

하지만 Post 등의 메서드를 추가했을 때,

[HttpPost]
public void Post()
{
    Thread.Sleep(1000);
}

이 메서드 호출을 curl로 테스트하면 1초 후에 응답이 오지만,

c:\temp> curl -v -X POST http://localhost:5252/weatherforecast

async void로 작성하면,

[HttpPost]
public async void Post()
{
    await Task.Delay(1000);

    throw new Exception("Error");
}

curl 호출 시 1초를 기다리지 않고 (심지어 위의 코드에서 예외도 발생시키고 있는데) 그냥 "HTTP/1.1 200 OK" 응답을 받습니다. (그 이유는 이미 지난 글에서 설명했기 때문에 생략합니다.)




당연히, ASP.NET Core Web App (razor) 프로젝트를 만들어도 이와 유사한 현상을 겪을 수 있습니다.

예를 들어 기본 생성한 Razor 프로젝트의 Index.cshtml/cs 파일을 async Task OnGet으로 변경해 다음과 같이 코딩하면,

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://learn.microsoft.com/aspnet/core?WT.mc_id=DT-MVP-4038148">building Web apps with ASP.NET Core</a>.</p>
    <p>@ViewData["Text"]</p>
</div>

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebApplication2.Pages;
public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    public async Task OnGet()
    {
        await Task.Delay(1000);
        this.ViewData["Text"] = "My Async Test";
    }
}

화면에는 정상적으로 "My Async Test"가 출력되지만, async void로 작성하면,

public async void OnGet()
{
    await Task.Delay(1000);
    this.ViewData["Text"] = "My Async Test";
}

"My Async Test"는 화면에 출력되지 않습니다. 결국, 컴파일이 된다고 해서 그것이 정상적으로 동작한다고 기대해서는 안 됩니다.




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







[최초 등록일: ]
[최종 수정일: 2/14/2025]

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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  114  115  116  117  118  [119]  120  ...
NoWriterDateCnt.TitleFile(s)
10982정성태5/26/201620845오류 유형: 335. SQL Server Management Studio - The database ... is not accessible.
10981정성태5/24/201626134.NET Framework: 592. C# - Lights Out 퍼즐 풀기 [2]파일 다운로드1
10980정성태5/24/201623324VS.NET IDE: 108. Visual Studio 2013/2015를 위한 "Macros for Visual Studio"
10979정성태5/23/201626320.NET Framework: 591. C# - 조합(Combination) 예제 코드 - 두 번째 이야기파일 다운로드1
10978정성태5/23/201625169.NET Framework: 590. C# - 모든 경우의 수를 조합하는 코드 (2)파일 다운로드1
10977정성태5/23/201629692.NET Framework: 589. C# - 모든 경우의 수를 조합하는 코드 (1)파일 다운로드1
10976정성태5/20/201624190Math: 18. C# - 오일러 공식을 이용한 복소수 값의 라디안 회전파일 다운로드1
10975정성태5/20/201624599Math: 17. C# - 복소수 타입의 승수를 지원하는 Power 메서드파일 다운로드1
10974정성태5/20/201625015.NET Framework: 588. C# - OxyPlot 라이브러리로 복소수 표현파일 다운로드1
10973정성태5/20/201629717.NET Framework: 587. C# Plotting 라이브러리 OxyPlot [3]파일 다운로드1
10972정성태5/19/201629209Math: 16. C# - 갈루아 필드 GF(2) 연산 [3]파일 다운로드1
10971정성태5/19/201621650오류 유형: 334. Visual Studio - 빌드 시 경고 warning MSB3884: Could not find rule set file "...". [2]
10970정성태5/19/201626364오류 유형: 333. OxyPlot 라이브러리의 컨트롤을 Toolbox에 등록 시 오류 [2]
10969정성태5/18/201625098.NET Framework: 586. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (3) - "Open with" 목록에 등록파일 다운로드1
10968정성태5/18/201620567오류 유형: 332. Visual Studio - 단위 테스트 생성 시 "Design time expression evaluation" 오류 메시지
10967정성태5/12/201625842.NET Framework: 585. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (2) - 웹 브라우저가 다운로드 후 자동 실행
10966정성태5/12/201633507.NET Framework: 584. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (1) - 기본 [1]파일 다운로드1
10965정성태5/12/201625485디버깅 기술: 81. try/catch로 조용히 사라진 예외를 파악하고 싶다면?
10964정성태5/12/201624106오류 유형: 331. ASP.NET에서 System.BadImageFormatException 예외가 발생하는 경우
10963정성태5/11/201626152VS.NET IDE: 107. Visual Studio 2015의 "DTAR_..." 특수 폴더가 생성되는 문제파일 다운로드2
10962정성태5/11/201625631오류 유형: 330. Visual Studio 단위 테스트 시 DisconnectedContext 예외 발생
10961정성태5/11/201625670.NET Framework: 583. 문제 재현 - Managed Debugging Assistant 'DisconnectedContext' has detected a problem in '...'파일 다운로드1
10960정성태5/10/201623670오류 유형: 329. ATL 메서드 추가 마법사 창에서 8ce0000b 오류 발생
10959정성태5/9/201625742.NET Framework: 582. CLR Profiler - 별도 정의한 .NET 코드를 호출하도록 IL 코드 변경파일 다운로드1
10958정성태5/6/201652804개발 환경 구성: 284. "Let's Encrypt"에서 제공하는 무료 SSL 인증서를 IIS에 적용하는 방법 (1) [3]
10957정성태5/3/201628123오류 유형: 328. 윈도우 백업 시 오류 - 0x80780166 두 번째 이야기 [1]
... 106  107  108  109  110  111  112  113  114  115  116  117  118  [119]  120  ...