Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Tasks and Use of Async/Await keywords

In the following code snippet since I am not able to use async/await keywords, is this method make behave synchronously?

public Task<IQueryable<Student>> Handle(GetStudentByIdRequest request)
    {
        return Task.FromResult(repository.GetAllCalfSubjects(student => student.studentId.Equals(request.studentId)));
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

is this method make behave synchronously?

Yes, it will always behave synchronously. GetAllCalfSubjects executes synchronously and then its result is wrapped up in a Task<T> by Task.FromResult, and that task is then returned. All of this is synchronous.

It doesn’t make much sense to return an IQueryable<T> wrapped up in a Task<T>. IQueryable<T> already has asynchronous APIs attached to it, so it’s normal to just (synchronously) return that type:

public IQueryable<Student> Handle(GetStudentByIdRequest request)
{
  return repository.GetAllCalfSubjects(student => student.studentId.Equals(request.studentId));
}

Then the calling code can call ToListAsync or whatever they want to do.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading