Asynchronous lambdas

Asynchronous lambdas are useful if you want to pass a potentially long-running delegate into a method. If the method accepts a Func<Task>, you can serve it with an asynchronous lambda and take advantage of the benefits of asynchrony.

Example with Microsoft's Dataflow API.

Synchronous lambdas

var block = new ActionBlock<int> (
	i => 
	{
		Thread.Sleep(1000);
		Console.Write($"{i} ");
	},
	new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 10 }
);        

Asynchronous lambdas

var block = new ActionBlock<int> (
	async i => 
	{
		await Task.Delay (1000);
		Console.Write($"{i} ");
	},
	new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 10 }
);        

要查看或添加评论,请登录

Martin Egli的更多文章

  • ref struct in C#

    ref struct in C#

    Structs and ref structs are two value types in C#. While the naming may seem confusing, ref structs are actually quite…

  • Class IL vs Record IL

    Class IL vs Record IL

    What is the IL difference between class and record? The class is very slim. The recod generates the various methods.

社区洞察

其他会员也浏览了