Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

c# - Is it correct if i am using await + ToListAsync() over IQueryable which is not defined as a task

I am using asp.net MVC-5 with EF-6, and I am not sure if using await + ToListAsync is valid. For example, I have the following repository method which returns an IQueryable :-

public IQueryable<TSet> getAllScanEmailTo()
{
    return t.TSets.Where(a=>a.Name.StartsWith("ScanEmail"));    
}

And I am calling it as follow:-

var emailsTo = await repository.getAllScanEmailTo().ToListAsync();

In the beginning, I thought I will get an error because I am using "await" a method which is not defined as a task, but the above worked well, so can anyone advice on this, please ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

At the beginning I thought I will get an error because I am using "await" a method which is not defined as a task, but the above worked well

Actually, you are awaiting a method which returns a Task<T>, where T is a List<TSet>. If you look at the extension method QueryableExtensions.ToListAsync, you'll see that it returns a Task<List<TSource>>. You are asynchronously waiting on this method to query the database, create the list and return it back to the caller. When you await on such a method, the method won't return until the operation has completed. async-await makes your code feel synchronous, while execution is actually asynchronous.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...