简体   繁体   中英

Should we provide both asynchronous and synchronous implementations of SmtpClient wrapper?

According to this article, we should not provide synchronous wrappers of asynchronous implementations.

We've abstracted the System.Net.SmtpClient behind an interface so that we can easily test code that sends emails.

Since SmtpClient actually has both asynchronous and synchronous implementations, should we expose both of these or just expect any consumer of our ISmtpClient interface just to Wait our asynchronous SendAsync method.

Not sure what the guidelines are here when it comes to building a general purpose library. In our case we know that we need to use both async and sync versions.

If your consumers need both asynchronous and synchronous versions and you can provide those then you should . Don't force you consumers to do sync over async , it hurts performance and could end in deadlocks.

You can see many examples of this in .Net libraries like SemaphoreSlim ( Wait/WaitAsync ) or TPL Dataflow ( Post/SendAsync ). Almost always when there's an async option there's also a sync option. The only case I can recall where there's only an async version is in WinRT , but that's because they are discouraging long sync calls .


As Ned Stoyanov mentioned, Toub's article is more about wrappers, and not true sync/async operations.

I think the article argues more about the case when your API only provides async implementations, in that case it is just as easy for the client to provide a "sync over async" implementation so no value is being added by you providing one. I think in the case when both are provided you should expose both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM