简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM