Async / Await Iterate on the returned task <IEnumerable <SomeClass>>
I want to use async / wait when querying a database with an HTTP call in my WPF application. This is my first time using async / await, so if you see any obvious error, feel free to point to them.
The problem is that im was unable to iterate over the returned collection, because now it is Task of <IEnumerable<SomeClass>> , and from what I found out, Task does not implement IEnumerable / IEnumerator.
My code looks like this: a method that calls the async / await method.
private void AddProjectDrawingAndComponentsFromServerToLocalDbAsync(CreateDbContext1 db, Project item) { var drawings = client.GetDrawingsAsync(item.ProjectId); ..... (waiting for GetDrawingsAsync to return, so i can iterate over the drawings) db.SaveChanges(); } GetDrawingsAsync Method:
public async Task<IEnumerable<Drawing>> GetDrawingsAsync(int projectId) { var drawings = Task.Factory.StartNew(() => _client.Get(new GetDrawingsReq() { ProjectId = projectId })); return await drawings; } Let's get back to the method that is waiting for the completion of the asynchronous method:
private void AddProjectDrawingAndComponentsFromServerToLocalDbAsync(CreateDbContext1 db, Project item) { var drawings = client.GetDrawingsAsync(item.ProjectId); <-- The returned Task<Task<IEnumerable<Drawing>> Drawing prj_drawing = null; foreach (var draw in drawings) { prj_drawing = new Drawing() { DrawingKey = draw.DrawingKey, Name = draw.Name, ProjectId = item.ProjectId }; item.AddDrawing(prj_drawing); db.Projects.Add(item); } db.SaveChanges(); } How can I convert the return type of Task<IEnumerable<Drawing>> to what I can iterate over in a foreach loop.
To iterate over the result of a Task , you need to get the result of a Task . And for this you should use await . This means that you must change AddProjectDrawingAndComponentsFromServerToLocalDbAsync() to the async method:
private async Task AddProjectDrawingAndComponentsFromServerToLocalDbAsync( CreateDbContext1 db, Project item) { var drawings = await client.GetDrawingsAsync(item.ProjectId); foreach (var draw in drawings) { // whatever } db.SaveChanges(); } This means that AddProjectDrawingAndComponentsFromServerToLocalDbAsync() (BTW is a pretty bad name for the method, I think) now returns Task , so you should probably change the method that calls it also in the async method. This leads to "async all the way" , but it is inevitable.