Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

named async lambda function

I want to create within a function a named lambda function, so that I can call it repeatedly afterwards in the same function.

I used to do this synchronously/without tasks with

Func<string, bool> pingable = (url) => return pingtest(url);

but in this case I want to call the pingable function as a task, so I would need a Task return type.

This is where I am stuck.

For all below, I am getting compile errors:

   * Func<string, Task<bool>> pingable = (input) => { return pingtest(url); };
   * Task<bool> pingable = new Task<bool>((input) => { return pingtest(url); });

I can declare the function normally though, but then I cannot call it as a task:

   Func<string, bool> pingable = (input) => { return pingtest(url); };      
   var tasks = new List<Task>();
   * tasks.Add(async new Task(ping("google.de")));

All the lines I have marked with a * produce copmile errors.

http://dotnetcodr.com/2014/01/17/getting-a-return-value-from-a-task-with-c/ seems to have a hint at a solution, but the sample there does not allow for not provided input parameters. (Sample taken from there and simplified:)

Task<int> task = new Task<int>(obj => 
{
    return obj + 1;
}, 300);

How to create and call named Task lambdas in C#, and I would like to declare them on a function rather than class level.

I want the named lambda in order to call it multiple times (several urls in this case).


Edit/update since you asked for code:

Func<string, Task<bool>> ping = url => Task.Run(() =>
{
    try
    {
        Ping pinger = new Ping();
        PingReply reply = pinger.Send(url);
        return reply.Status == IPStatus.Success;
    }
    catch (Exception)
    {
        return false;
    }
});

var tasks = new List<Task>();
tasks.Add(ping("andreas-reiff.de"));
tasks.Add(ping("google.de"));
Task.WaitAll(tasks.ToArray());
bool online = tasks.Select(task => ((Task<bool>)task).Result).Contains(true);

This already makes use of the solution proposed here.

like image 730
Andreas Reiff Avatar asked Jan 05 '15 20:01

Andreas Reiff


People also ask

How do I use async lambdas?

Async lambdas. You can easily create lambda expressions and statements that incorporate asynchronous processing by using the async and await keywords. For example, the following Windows Forms example contains an event handler that calls and awaits an async method, ExampleMethodAsync. C#.

How do you make a lambda function anonymous in Python?

You use a lambda expression to create an anonymous function. Use the lambda declaration operator => to separate the lambda's parameter list from its body. A lambda expression can be of any of the following two forms: Expression lambda that has an expression as its body:

What is a lambda expression in C++?

In C++11 and later, a lambda expression—often called a lambda —is a convenient way of defining an anonymous function object (a closure) right at the location where it is invoked or passed as an argument to a function. Typically lambdas are used to encapsulate a few lines of code that are passed to algorithms or asynchronous methods.

How do I enable asynchronous invocation in AWS Lambda?

Asynchronous invocation 1 Configuring error handling for asynchronous invocation. Use the Lambda console to configure error handling settings on a function, a version, or an alias. ... 2 Configuring destinations for asynchronous invocation. ... 3 Asynchronous invocation configuration API. ... 4 AWS Lambda function dead-letter queues. ...


1 Answers

Since pingtest looks to be synchronous itself, I assume you want a Task so that the method would run on a different thread. If that's true you need to use Task.Run to offload the work to a ThreadPool thread:

Func<string, Task<bool>> func = url => Task.Run(() => pingtest(url));

For completeness, if pingtest was async (i.e. pingtestAsync) you would need to create an async lambda expression:

Func<string, Task<bool>> func = async url => await pingtestAsync(url);

However, since in this case pingtestAsync already return a Task<bool> there's no sense in adding another layer of async or a lambda expression at all. This would be enough:

Func<string, Task<bool>> func = pingtestAsync;
like image 198
i3arnon Avatar answered Oct 25 '22 21:10

i3arnon