The async/await keywords change methods behavior. When async/await pattern is used, the method never throws an exception. The method always returns a task which can be eventually Faulted, Canceled or RunToCompletion. So why do I think about violating Liskov Substitution Principle?
Consider the following interface:
public interface INeedToDoSomething
{
Task<string> DownloadContentAsync(string url);
}
You can implement this interface in to different ways. Optimized version without async/await
public class NeedToDoSomethingNoAwait : INeedToDoSomething
{
public Task<string> DownloadContentAsync(string url)
{
Validate.IsValidUrl(url);
return worker.DownloadUrlContentAsync(url);
}
}
and less optimal version with async/await
public class NeedToDoSomethingWithAwait : INeedToDoSomething
{
public async Task<string> DownloadContentAsync(string url)
{
Validate.IsValidUrl(url);
return await worker.DownloadContentAsync(url);
}
}
where the machine state is created. Let’s focus on that part of our method Validate.IsValidUrl(url)
– which throws an exception for invalid URL.
The problem is that when URL is invalid first implementation without async/await throws an exception immediately, but second method returns eventually Faulted task.
INeedToDoSomething needToDoSomethingsWithAwait = new NeedToDoSomethingWithAwait();
INeedToDoSomething needToDoSomethingsNoAwait = new NeedToDoSomethingNoAwait();
Task<string> resultWithAsync =
needToDoSomethingsWithAwait.DownloadContentAsync("Invalid url");
Task<string> resultWithoutAsync =
needToDoSomethingsNoAwait.DownloadContentAsync("Invalid url"); // throws an exception
It means that call of DownloadContentAsync can fail immediately and break your logic if you expect that method with Async signature to be asynchronous and always to return a task.
This is a place where Liskov Substitution Principle can be violated in my opinion, so you have to be careful while implementing interfaces with Async signature. I suggest to agree with your project team if you want to optimize your code or respect Liskov Substitution Principle.