Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I easily support duplicate async/sync methods?

Entity framework has synchronous and asynchronous versions of the same IO-bound methods such as SaveChanges and SaveChangesAsync. How can I create new methods that minimally accomplish the same task without "duplicating" 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();
}
like image 226
James Sampica Avatar asked Sep 23 '14 14:09

James Sampica


People also ask

Is await async the same as sync?

The differences between asynchronous and synchronous include: Async is multi-thread, which means operations or programs can run in parallel. Sync is single-thread, so only one operation or program will run at a time. Async is non-blocking, which means it will send multiple requests to a server.

Does asynchronous programming improve performance?

For applications with many tasks, programmers can consider using async programming. It allows one or more tasks to progress independently, rather than sequentially. The user benefits from increased responsiveness and improved overall performance.

What are asynchronous methods in c#?

C# has a language-level asynchronous programming model, which allows for easily writing asynchronous code without having to juggle callbacks or conform to a library that supports asynchrony. It follows what is known as the Task-based Asynchronous Pattern (TAP).

Why we use async Task c#?

Using asynchronous programming indicates that a method can execute without waiting for another method to complete. Using async and await, we can run the methods above parallelly.


1 Answers

You can't - at least, not sensibly. Synchronous and asynchronous implementations are fundamentally different. You can fake over it, via "sync over async" and "async over sync", but both of these are anti-patterns and should be avoided.

like image 65
Marc Gravell Avatar answered Oct 11 '22 18:10

Marc Gravell