C# Tasks and Use of Async/Await keywords

Viewed 67

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)));
    }
1 Answers

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.

Related