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)));
}
CodePudding user response:
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.
CodePudding user response:
Depends how its called.
public static async void Main(string[] args)
{
// someMethod() is called before Handle finishes
Handle(request);
someMethod();
// someMethod() is called only Handle finishes
await Handle(request);
someMethod()
}
But if you're calling it from a synchronous context (non async
method), it will always wait for Handle
to finish.