언제 ASP.NET MVC에서 비동기 컨트롤러를 사용해야합니까?
ASP.NET MVC에서 비동기 작업을 사용하는 데 약간의 문제가 있습니다. 언제 내 애플 리케이션의 성능을 향상 않으며, 경우에 그렇습니다 하지 ?
- ASP.NET MVC의 모든 곳에서 비동기 작업을 사용하는 것이 좋습니까?
- 대기 가능한 방법과 관련하여 (EF / NHibernate / other ORM을 통해) 데이터베이스를 쿼리 할 때 async / await 키워드를 사용해야합니까?
- 하나의 단일 조치 메소드 에서 await 키워드를 사용하여 데이터베이스를 비동기 적으로 쿼리 할 수있는 횟수는 몇 번 입니까?
비동기 조치 메소드는 조치가 여러 개의 독립적 인 장기 실행 조작을 수행해야 할 때 유용합니다.
AsyncController 클래스의 일반적인 용도는 오래 실행되는 웹 서비스 호출입니다.
데이터베이스 호출이 비동기식이어야합니까?
IIS 스레드 풀은 종종 데이터베이스 서버보다 더 많은 동시 차단 요청을 처리 할 수 있습니다. 데이터베이스가 병목 상태 인 경우 비동기 호출은 데이터베이스 응답 속도를 높이 지 않습니다. 스로틀 링 메커니즘이 없으면 비동기 호출을 사용하여 더 많은 작업을 압도적 데이터베이스 서버로 효율적으로 디스패치하면 데이터베이스에 대한 부담이 더 커집니다. DB가 병목 상태 인 경우 비동기 호출은 마법의 총알이 아닙니다.
@PanagiotisKanavos 의견에서 파생되었습니다.
또한 비동기는 병렬을 의미하지 않습니다. 비동기 실행은 복잡한 스레드 나 성능 비용없이 소중한 스레드 풀 스레드가 외부 리소스를 차단하지 않도록합니다. 이는 동일한 IIS 시스템이 더 많은 동시 요청을 처리 할 수 있다는 것을 의미합니다.
또한 차단 호출은 CPU 집약적 스핀 웨이트로 시작해야합니다. 스트레스 시간 동안 통화를 차단하면 지연이 지연되고 앱 풀이 재활용됩니다. 비동기 호출은 단순히 이것을 피하십시오
당신은 내 찾을 수 있습니다 도움이 주제에 대한 MSDN 문서를 ; 이 기사에서는 ASP.NET에서 사용 하는 방법 뿐만 아니라 ASP.NET에서 언제 사용 해야하는지 설명하는 많은 공간을 차지했습니다 .async
async
ASP.NET MVC에서 비동기 작업을 사용하는 데 약간의 문제가 있습니다. 앱 성능을 향상시킬 때와 그렇지 않을 때
먼저 async
/ await
가 스레드 를 해제하는 것임을 이해하십시오 . GUI 응용 프로그램에서는 주로 GUI 스레드를 해제 하여 사용자 경험을 향상시키는 것입니다. 서버 응용 프로그램 (ASP.NET MVC 포함)에서는 주로 서버가 확장 될 수 있도록 요청 스레드를 해제하는 것 입니다.
특히, 그것은 하지 않습니다 :
- 개별 요청을 더 빨리 완료하십시오. 실제로, 그들은 완만하게 (완전히 조금씩) 완만하게 될 것입니다.
- 를 누르면 발신자 / 브라우저로 돌아갑니다
await
.await
브라우저가 아닌 ASP.NET 스레드 풀에만 "수율"이됩니다.
첫 번째 질문은 ASP.NET MVC의 모든 곳에서 비동기 작업을 사용하는 것이 좋습니까?
I / O를 수행하는 모든 곳에서 사용하는 것이 좋습니다. 그러나 반드시 도움 이되는 것은 아닙니다 (아래 참조).
그러나 CPU 바운드 방법에는 사용하지 않습니다 . 때때로 개발자 는 컨트롤러를 async
호출하기 만하면 혜택을 얻을 수 있다고 생각 Task.Run
하며 이는 끔찍한 아이디어입니다. 이 코드는 다른 스레드를 사용하여 요청 스레드를 해제하므로 아무런 이점이 없습니다 (실제로 추가 스레드 스위치의 페널티를 받고 있습니다)!
데이터베이스를 쿼리 할 때 (EF / NHibernate / other ORM을 통해) async / await 키워드를 사용해야합니까?
사용 가능한 대기 가능한 방법을 사용할 수 있습니다. 현재 대부분의 주요 플레이어는을 지원 async
하지만 그렇지 않은 플레이어 도 있습니다. ORM이을 지원하지 않는 경우 async
, Task.Run
또는 이와 유사한 것을 포장하려고하지 마십시오 (위 참조).
내가 " 사용할 수있다 "고 말했음을 주목하십시오 . 단일 데이터베이스 백엔드로 ASP.NET MVC에 대해 이야기하고 있다면 확장 성 이점을 얻지 못할 것입니다 async
. IIS는 단일 SQL Server 인스턴스 (또는 다른 클래식 RDBMS)보다 훨씬 많은 동시 요청을 처리 할 수 있기 때문입니다. 그러나 백엔드는 더 현대적인 경우 - SQL Server 클러스터, 푸른 SQL, NoSQL의 등 -과 백엔드 확장 할 수 있습니다, 그리고 확장 성 병목 현상, IIS입니다 다음 당신이에서 확장 성 혜택을받을 수 있습니다 async
.
세 번째 질문-하나의 단일 조치 메소드에서 데이터베이스를 비동기식으로 쿼리하기 위해 대기 키워드를 몇 번 사용할 수 있습니까?
당신이 원하는만큼. 그러나 많은 ORM에는 연결 당 하나의 작업 규칙이 있습니다. 특히 EF는 DbContext 당 단일 작업 만 허용합니다. 작업이 동기식인지 비동기식인지에 관계없이 마찬가지입니다.
또한 백엔드의 확장 성을 다시 염두에 두십시오. 단일 SQL Server 인스턴스를 사용 중이고 IIS가 이미 SQLServer를 최대 용량으로 유지할 수있는 경우 SQLServer에 대한 압력을 두 배로 늘리거나 세 배로 늘리더라도 전혀 도움이되지 않습니다.
ASP.NET MVC의 모든 곳에서 비동기 작업을 사용하는 것이 좋습니까?
프로그래밍에서 평소와 같이 다릅니다 . 특정 경로를 따라갈 때 항상 상충 관계가 있습니다.
async-await
서비스에 대한 동시 요청을 받고 잘 확장 할 수있는 곳에서 빛납니다 . 어떻게 async-await
수평 확장에 도움을? 네트워크 호출이나 데이터베이스 히트와 같은 비동기 IO 호출을 동기식 으로 호출하면 실행을 담당하는 현재 스레드가 요청이 완료되기를 기다리는 동안 차단됩니다. 당신이 사용하는 경우 async-await
, 당신은 IO 호출이 완료되면, 당신의 방법이 off 상태에서 실행을 계속 확인하게하는 당신을위한 상태 머신을 생성하는 프레임 워크를 가능하게한다.
A thing to note is that this state machine has a subtle overhead. Making a method asynchronous does not make it execute faster, and that is an important factor to understand and a misconception many people have.
Another thing to take under consideration when using async-await
is the fact that it is async all the way, meaning that you'll see async penetrate your entire call stack, top to buttom. This means that if you want to expose synchronous API's, you'll often find yourself duplicating a certain amount of code, as async and sync don't mix very well.
Shall I use async/await keywords when I want to query database (via EF/NHibernate/other ORM)?
If you choose to go down the path of using async IO calls, then yes, async-await
will be a good choice, as more and more modern database providers expose async method implementing the TAP (Task Asynchronous Pattern).
How many times I can use await keywords to query database asynchronously in ONE single action method?
As many as you want, as long as you follow the rules stated by your database provider. There is no limit to the amount of async calls you can make. If you have queries which are independent of each other and can be made concurrently, you can spin a new task for each and use await Task.WhenAll
to wait for both to complete.
My 5 cents:
- Use
async/await
if and only if you do an IO operation, like DB or external service webservice. - Always prefer async calls to DB.
- Each time you query the DB.
P.S. There are exceptional cases for point 1, but you need to have a good understanding of async internals for this.
As an additional advantage, you can do few IO calls in parallel if needed:
Task task1 = FooAsync(); // launch it, but don't wait for result
Task task2 = BarAsync(); // launch bar; now both foo and bar are running
await Task.WhenAll(task1, task2); // this is better in regard to exception handling
// use task1.Result, task2.Result
async
actions help best when the actions does some I\O operations to DB or some network bound calls where the thread that processes the request will be stalled before it gets answer from the DB or network bound call which you just invoked. It's best you use await with them and it will really improve the responsiveness of your application (because less ASP input\output threads will be stalled while waiting for the DB or any other operation like that). In all my applications whenever many calls to DB very necessary I've always wrapped them in awaiatable method and called that with await
keyword.
As you know, MVC supports asynchronous controllers and you should take advantage of it. In case your Controller, performs a lengthy operation, (it might be a disk based I/o or a network call to another remote service), if the request is handled in synchronous manner, the IIS thread is busy the whole time. As a result, the thread is just waiting for the lengthy operation to complete. It can be better utilized by serving other requests while the operation requested in first is under progress. This will help in serving more concurrent requests. Your webservice will be highly scalable and will not easily run into C10k problem. It is a good idea to use async/await for db queries. and yes you can use them as many number of times as you deem fit.
Take a look here for excellent advise.
Is it good to use async action everywhere in ASP.NET MVC?
It's good to do so wherever you can use an async method especially when you have performance issues at the worker process level which happens for massive data and calculation operations. Otherwise, no need because unit testing will need casting.
Regarding awaitable methods: shall I use async/await keywords when I want to query a database (via EF/NHibernate/other ORM)?
Yes, it's better to use async for any DB operation as could as possible to avoid performance issues at the level of worker processes. Note that EF has created many async alternatives for most operations, such as:
.ToListAsync()
.FirstOrDefaultAsync()
.SaveChangesAsync()
.FindAsync()
How many times can I use await keywords to query the database asynchronously in one single action method?
The sky is the limit
My experience is that today a lot of developers use async/await
as a default for controllers.
My suggestion would be, use it only when you know it will help you.
The reason is, as Stephen Cleary and others already mentioned, it can introduce performance issues, rather than resolving them, and it will help you only in a specific scenario:
- High-traffic controllers
- Scalable backend
참고URL : https://stackoverflow.com/questions/30566848/when-should-i-use-async-controllers-in-asp-net-mvc
'Programing' 카테고리의 다른 글
Android Studio에서 경고 화면 옵션은 어디에 있습니까? (0) | 2020.05.09 |
---|---|
grep이 'No such file or directory'오류를 출력하지 않게하려면 어떻게해야합니까? (0) | 2020.05.09 |
@ 미디어 최소 너비 및 최대 너비 (0) | 2020.05.09 |
Java VM이 몇 개의 스레드를 지원할 수 있습니까? (0) | 2020.05.09 |
C void 인수“void foo (void)”를 사용하거나“void foo ()”를 사용하지 않는 것이 더 낫습니까? (0) | 2020.05.09 |