Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

I have a class which contains a function that needs to be called asynchronously at a later time. Similar to this:

C#
public class MyClass
{
    public Task SomeFunctionAsync()
    {
        // Do a long-running thing...
    }
}


I actually have a few of these classes, and I am wanting to store references to these Task SomeFunctionAsync() functions in a List<> or similar so that I can invoke these functions later. But I am struggling with the type I need to store.

I'm sure the answer will be obvious when I see it, but I'd really appreciate someone to clear up my muddy thinking here.

Kind wishes ~ Patrick

What I have tried:

Currently I am trying to store these in a List<Task>, which compiles but I can't work out how to invoke the stored delegate.
Posted
Updated 22-Mar-16 3:49am

If you store the results in a List<Task>, the methods will be invoked once, and you will be able to retrieve the results from the list.

If you want to invoke the methods multiple times on demand, store them in a List<Func<Task>>:
C#
var listOfDelegates = new List<Func<Task>>
{
    instanceOfMyClass.SomeFunctionAsync
};
...
List<Task> listOfTasks = listOfDelegates.Select(fn => fn()).ToList();
await Task.WhenAll(listOfTasks);
 
Share this answer
 
v2
Comments
Sascha Lefèvre 22-Mar-16 9:56am    
+5Typo in the last line
Richard Deeming 22-Mar-16 9:57am    
Fixed. :)
Patrick Skelton 22-Mar-16 10:34am    
Sorry, so are you saying that the async method will be triggered as soon as I add it to the List?
Richard Deeming 22-Mar-16 10:36am    
If you use List<Task>, then yes. It is possible to create Tasks that haven't started yet, but it's not recommended, and the majority of task-returning APIs don't do it.
Patrick Skelton 22-Mar-16 10:45am    
Ooo... seems like I suddenly have more reading to do. I've tried to do thorough research on this. I've even bought a couple of books, which admittedly I have only just started reading. But I have not read anything to indicate why putting Tasks in a list and starting them later is a bad idea. I ~think~ I understand why, but it is also obvious there is a big hole in my knowledge. Thank you.
visit Here to understand....
Asynchronous Method Invocation[^]
 
Share this answer
 
Comments
Patrick Skelton 22-Mar-16 10:36am    
It is a nice article, but I don't have the System.Windows.Forms namespace available, because I am in a Xamarin.Forms application. Is there a 'more generic' alternative?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900