简体   繁体   English

如何在匿名委托中调用异步方法?

[英]How can I call an async method inside an anonymous delegate?

I have a function takes a delegate as input parameter.我有一个函数将委托作为输入参数。

public delegate bool Callback();

public static class MyAPI
{
     public static handle(Callback callback) {
           ... 
     }
}

So I call the api with an anonymous delegate like this所以我用这样的匿名委托调用 api

MyAPI.handle(delegate
{
    // my implementation
});

My question is how can i call an async method in my anonymous delegate?我的问题是如何在匿名委托中调用异步方法?

MyAPI.handle(delegate
{
    // my implementation
    await MyMethodAsync(...);
});

I get an error saying the 'await' operator can only be used within async anonymous method'?我收到一条错误消息,指出“await”运算符只能在异步匿名方法中使用?

The function MyAPI.handle() only expect a non async delegate.函数 MyAPI.handle() 只需要一个非异步委托。 I can't change that method.我不能改变那个方法。 How can I fix my problem?我该如何解决我的问题?

Thank you.谢谢你。

You could call an asynchronous method by passing an async lambda expression:您可以通过传递异步 lambda 表达式来调用异步方法:

MyAPI.handle(async () =>
{
    // my implementation
    await MyMethodAsync(...);
});
MyAPI.handle(async () =>
{
    // my implementation
    await MyMethodAsync(...);
});

Another solution for people like me that don't really like how lambdas look.对于像我这样不太喜欢 lambda 外观的人的另一种解决方案。

MyAPI.handle(
    async delegate() {
        // my implementation
        await MyMethodAsync(...);
    }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM