alexteslin
Member
- Joined
- Oct 28, 2022
- Messages
- 10
- Programming Experience
- 3-5
Hi,
I have a loop from which I call an async method that in turn calls several async methods. My loop example:
My SaveItem method example:
The above loop works fine and in async. The problem is within the SaveItem() method when first checks for existing sourceId by calling GetSourceId() method and if it can't find then calls CreateSourceId() method. And the problem is that the CreateSourceId method depends on previous GetSourceId() method. Even though I am using await keywords these are called from the loop. And if the sourceId is null or empty guid on first iteration it creates correctly the sourceId by calling CreateSourceId() method. But if the second immediate item has no sourceId either it then calls again for CreateSourceId(), in which case it creates a duplicate.
What I am after is that to wait until the sourceId from the previous item has been created so that then I can use that value.
Is this possible at all? I don't want to make the loop synchronous as there are quite a number of items and there are more methods and saving to db etc, which will take much longer to run the code.
Thanks,
Alex
My
I have a loop from which I call an async method that in turn calls several async methods. My loop example:
Loop:
List<Task<ReturnItem>> savedItemTasks = new List<Task<ReturnItem>>();
foreach(var item in items)
{
savedItemTasks.Add(SaveItem(item))
}
var result = await Task.WhenAll<ReturnItem>(savedItemTasks);
My SaveItem method example:
SaveItem:
private async Task<ReturnItem> SaveItem(ItemType item)
{
if(!IsValidItem(item))
return;
Guid? itemId = await GetItemId(item);
if(itemId == null || itemId == Guid.Empty)
return;
var sourceId = await GetSourceId(item);
if(sourceId == null || sourceId == Guid.Empty)
sourceId = await CreateSourceId(item);
// Some other async calls
return new ReturnItem {
...
};
}
The above loop works fine and in async. The problem is within the SaveItem() method when first checks for existing sourceId by calling GetSourceId() method and if it can't find then calls CreateSourceId() method. And the problem is that the CreateSourceId method depends on previous GetSourceId() method. Even though I am using await keywords these are called from the loop. And if the sourceId is null or empty guid on first iteration it creates correctly the sourceId by calling CreateSourceId() method. But if the second immediate item has no sourceId either it then calls again for CreateSourceId(), in which case it creates a duplicate.
What I am after is that to wait until the sourceId from the previous item has been created so that then I can use that value.
Is this possible at all? I don't want to make the loop synchronous as there are quite a number of items and there are more methods and saving to db etc, which will take much longer to run the code.
Thanks,
Alex
My