How can I easily support async / sync duplicate methods?

The Entity structure has synchronous and asynchronous versions of the same IO-related methods as SaveChanges and SaveChangesAsync . How can I create new methods that perform the same task minimally without "duplicating" the code?

 public bool SaveChanges() { //Common code calling synchronous methods context.Find(...); //Synchronous Save return context.SaveChanges(); } public async Task<bool> SaveChangesAsync() { //Common code asynchronous methods await context.FindAsync(...); //Asynchronous Save return await context.SaveChangesAsync(); } 
+6
source share
1 answer

You cannot - at least not reasonably. Synchronous and asynchronous implementations are significantly different . You can fake it through "sync over async" and "async over sync", but both are anti-patterns and should be avoided.

+5
source

Source: https://habr.com/ru/post/975719/


All Articles