I've got a class that takes for ages to spin up due to it performing some long running operations in the constructor. I need to create 3 of these objects and add them to a dictionary.
I'm trying to make use of async so that I create 3 threads, each spinning up one of these objects, but finding it a little confusing.
Initially I thought I'd wait until all threads were completed, and then add the results to the dictionary, but I couldn't get the code to compile, so I've resorted to doing the dictionary.Add within the thread (is this ok?)
I've written the following code
public void CreateAccountStuffs(ICollection<Account> accounts)
{
CreateStuff(accounts);
}
private async void CreateStuff(ICollection<Account> accounts)
{
var tasks = accounts.Select(a => CreateStuffForAccount(a));
await Task.WhenAll(tasks);
}
private Task CreateStuffForAccount(Account account)
{
//Long Running process due to website calls in AccountWrapper construction
var accountWrapper = new AccountWrapper(account);
return Task.FromResult(accountWrapper);
}
The final line seems pointless, but I can't get the code to compile without it. I feel like I'm missing something really obvious here, but my multithreading skills are so rusty I'm struggling to see what.
My gut feeling is that there is a far simpler way of writing what I need to do, but I don't know what that is.
e.g. I notice this question appears to suggest that you can write a method that returns Task and simply in the method body write return "This String", however, that construct doesn't compile for me. I get the error cannot convert from string to Task
Note - Edited to remove code not part of the problem - there were 2 constructors involved before, which confused things - it's the constructor in AccountWrapper that is long running.