I'm trying to learn to write my own asynchronous methods, but I'm having difficulty, because ALL of the millions of examples that I have seen online ALL use await Task.Delay
inside the custom async method and I neither want to add a delay into my code, nor have any other async method to call in its place.
Let's use a simple example, where I want to create a new collection of objects, with only two properties, from a huge existing collection of objects, that each have a great many properties. Let's say this is my synchronous code:
public List<SomeLightType> ToLightCollection(List<SomeType> collection)
{
List<SomeLightType> lightCollection = new()
foreach (SomeType item in collection)
{
lightCollection.Add(new SomeLightType(item.Id, item.Name));
}
return lightCollection;
}
To make this method asynchronous, do I just need to wrap it in a Task.Run
, add the async
keyword and suffix on the method name, and change the return type, as follows?:
public Task<List<SomeLightType>> ToLightCollectionAsync(List<SomeType> collection)
{
List<SomeLightType> lightCollection = new()
Task.Run(() =>
{
foreach (SomeType item in collection)
{
lightCollection.Add(new SomeLightType(item.Id, item.Name));
}
});
return lightCollection;
}
Or do I also need to await
the return of the Task
inside the method? (The compiler gave me a warning until I added await
.):
public async Task<List<SomeLightType>> ToLightCollectionAsync(List<SomeType> collection)
{
List<SomeLightType> lightCollection = new()
await Task.Run(() =>
{
foreach (SomeType item in collection)
{
lightCollection.Add(new SomeLightType(item.Id, item.Name));
}
});
return lightCollection;
}
EDIT:
Oh yes, I have just realised that I need to await
this operation, otherwise the empty collection will be returned before it is populated. But still, is this the correct way to make this code run asynchronously?