Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing an asp.net app to use async little by little

We have an asp.net application, it makes no use of async or parallel methods(except for some owin middleware).

I want to start using the async version of some methods using the async-await syntax.

I know that there is danger in mixing async and sync operations as that might cause a deadlocks.

It is not possible to rewrite the whole app in one go.

Where should I Start? is the safe way to do it to make the controllers actions async and work my way down? or the other way around?

Is there some clear warning sign(s) that I can watch for along the way like: "never have a sync method call an async method, but it's fine to have async call sync"

like image 777
user1852503 Avatar asked Mar 17 '23 00:03

user1852503


2 Answers

Where should I Start? is the safe way to do it to make the controllers actions async and work my way down? or the other way around?

I recommend starting at the "leaves" and creating "vertical partitions". That is, within a service or data access layer, identify I/O-bound operations. Then create asynchronous copies of those methods that use naturally-asynchronous APIs. Once you have those, then continue "up" your layers, creating asynchronous copies, until you can make a controller action asynchronous.

You'll end up with a fair amount of code duplication - both synchronous and asynchronous versions of the same method - but this is only temporary. Once all the other code only uses the asynchronous version of a method, the synchronous version can be removed.

like image 78
Stephen Cleary Avatar answered Apr 01 '23 08:04

Stephen Cleary


You can safely mix sync and async IO. The deadlock arises from the way await automatically uses the ambient SynchronizationContext. Platform methods such as Stream.Read almost never do this.

Start with making long-running IO async. Short-running IO is more likely not to benefit.

like image 35
usr Avatar answered Apr 01 '23 08:04

usr