Named Asynchronous Lambda Function

I want to create a named function lambda inside a function so that I can repeat it several times in the same function.

I did it synchronously / no task using

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

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

This is where I am stuck.

For all below, I get compilation errors:

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

I can declare this function normally, but then I cannot call it a task:

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

All lines marked with an asterisk * cause copy errors.

http://dotnetcodr.com/2014/01/17/getting-a-return-value-from-a-task-with-c/ seems to have a hint of a solution, but the sample does not allow you to enter input parameters there. (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 as a function, not a class level.

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


Change / update from the moment you request the 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); 

It already uses the solution proposed here.

+6
source share
1 answer

Since pingtest looks like synchronous, I assume that you want Task to make this method work in another thread. If this is true, you need to use Task.Run to offload the work to the ThreadPool thread:

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

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

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

However, since pingtestAsync already returns a Task<bool> in this case, it makes no sense to add another layer of async or lambda expressions at all. That would be enough:

 Func<string, Task<bool>> func = pingtestAsync; 
+5
source

Source: https://habr.com/ru/post/980545/


All Articles