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.