我需要为这个异步函数存储什么类型? [英] What is the type I need to store for this asynchronous function?

查看:83
本文介绍了我需要为这个异步函数存储什么类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个类,其中包含一个需要在以后异步调用的函数。与此类似:



Hi,

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

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





我实际上有一些这样的类,我想存储对这些的引用任务SomeFunctionAsync()函数在列表<> 或类似内容中,以便我稍后可以调用这些函数。但我正在努力应对我需要存储的类型。



我确定当我看到答案时,答案会很明显,但我真的很感激有人来在这里清理我的泥泞思想。



亲切的愿望~Patrick



我尝试过什么:



目前我正在尝试将这些存储在列表< Task> 中,这些编译但我无法弄清楚如何调用存储的委托。



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.

推荐答案

如果您将结果存储在列表<任务> ,方法将被调用一次,你将能够从列表中检索结果。



如果你想调用多个方法按需按次,将它们存储在列表< Func< Task>>

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>>:
var listOfDelegates = new List<Func<Task>>
{
    instanceOfMyClass.SomeFunctionAsync
};
...
List<Task> listOfTasks = listOfDelegates.Select(fn => fn()).ToList();
await Task.WhenAll(listOfTasks);


访问此处了解.. ..

异步方法调用 [ ^ ]
visit Here to understand....
Asynchronous Method Invocation[^]


这篇关于我需要为这个异步函数存储什么类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆