5

Is this possible in C#? The following code produces a compiler error.

HashSet<Task<(string Value, int ToNodeId)>> regionTasks =
  new HashSet<Task<(string Value, int ToNodeId)>>();
foreach (Connection connection in Connections[RegionName])
{
    regionTasks.Add(async () =>
    {        
        string value = await connection.GetValueAsync(Key);
        return (value, connection.ToNode.Id);
    }());
}

The C# compiler complains, "Error CS0149: Method name expected." It's unable to infer the lambda method's return type.

Note my technique of invoking the lambda method immediately via the () after the the lambda block is closed {}. This ensures a Task is returned, not a Func.

The VB.NET compiler understands this syntax. I am stunned to find an example of the VB.NET compiler outsmarting the C# compiler. See my An Async Lambda Compiler Error Where VB Outsmarts C# blog post for the full story.

Dim regionTasks = New HashSet(Of Task(Of (Value As String, ToNodeId As Integer)))
For Each connection In Connections(RegionName)
    regionTasks.Add(Async Function()
        Dim value = Await connection.GetValueAsync(Key)
        Return (value, connection.ToNode.Id)
    End Function())
Next

The VB.NET compiler understands the End Function() technique. It correctly infers the lambda method's return type is Function() As Task(Of (Value As String, ToNodeId As Integer)) and therefore invoking it returns a Task(Of (Value As String, ToNodeId As Integer)). This is assignable to the regionTasks variable.

C# requires me to cast the lambda method's return value as a Func, which produces horribly illegible code.

regionTasks.Add(((Func<Task<(string Values, int ToNodeId)>>)(async () =>
{
    string value = await connection.GetValueAsync(Key);
    return (value, connection.ToNode.Id);
}))());

Terrible. Too many parentheses! The best I can do in C# is explicitly declare a Func, then invoke it immediately.

Func<Task<(string Value, int ToNodeId)>> getValueAndToNodeIdAsync = async () =>
{
    string value = await connection.GetValueAsync(Key);
    return (value, connection.ToNode.Id);
};
regionTasks.Add(getValueAndToNodeIdAsync());

Has anyone found a more elegant solution?

9
  • 1
    The problem with the IIFE style is that the compiler hasn't determined if it's an expression tree or an anonymous method. Very irritating at times but it is rarely encountered. Commented Jul 4, 2020 at 21:17
  • That sheds some light on why the C# compiler can't infer the return type. Though I'm still confused why the VB.NET compiler can. I guess I need to read up on .NET expression trees. Commented Jul 4, 2020 at 21:26
  • It is odd indeed. I expect that VB assumes it is an anonymous method. A practical choice if so. Commented Jul 4, 2020 at 21:27
  • @ErikMadsen it seems that expression trees are not related to the question. Commented Jul 4, 2020 at 21:37
  • @GuruStron I don't think that's it. I declare the type of the regionTasks variable. The questioner indicated the strongly-typed version of his code does compile. He only encountered a compiler error with the var-typed version. Commented Jul 4, 2020 at 22:03

3 Answers 3

3

If .NET Standard 2.1 (or some .NET Framework versions, see compatibility list) is available for you, you can use LINQ with ToHashSet method:

var regionTasks = Connections[RegionName]
    .Select(async connection => 
    {        
        string value = await connection.GetValueAsync(Key);
        return (Value: value, ToNodeId: connection.ToNode.Id);
    })
    .ToHashSet();

Or just initialize HashSet with corresponding IEnumerable.

UPD

Another workaround from linked in comments answer:

static Func<R> WorkItOut<R>(Func<R> f) { return f; }

foreach (Connection connection in Connections[RegionName])
{
    regionTasks.Add(WorkItOut(async () =>
    {        
        string value = await connection.GetValueAsync(Key);
        return (value, connection.ToNode.Id);
    })());
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's really clever! Thanks.
Why did I know my question was going to lead to an answer by Eric Lippert? Ha ha. I'm an avid reader of his blog and totally respect his efforts to educate all of us on the inner workings of the .NET runtime and C# compiler. Though in this particular case (the question you link to), I agree with user541686 who commented on Eric's answer, "it's slightly misleading to illustrate this as something that's not possible, as this actually works completely fine in D. It's just that you guys didn't choose to give delegate literals their own type, and instead made them depend on their contexts..."
Thanks for your second recommendation. That's what Theodor Zoulias suggested too, though with a more practical function name, Materialize. WorkItOut (I know it's Lippert's term, not yours) strikes me as very didactic.
1

When I first read the title of your question I thought "Eh? Who would propose trying to assign a value of type x to variable of type y, not in an inheritance relationship with x? That's like trying to assign an int to a string..."

I read the code, and that changed to "OK, this isn't assigning a delegate to a Task, this is just creating a Task and storing it in a collection of Tasks.. But it does look like they're assigning a delegate to a Task...

Then I saw

Note my technique of invoking the lambda method immediately via the () after the the lambda block is closed {}. This ensures a Task is returned, not a Func.

The fact that you have to explain this with commentary means it's a code smell and the wrong thing to do. Your code has gone from being readably self documenting, to a code golf exercise, using an arcane syntax trick of declaring a delegate and immediately executing it to create a Task. That's what we have Task.Run/TaskFactory.StartNew for, and it's what all the TAP code I've seen does when it wants a Task

You'll note that this form works and doesn't produce an error:

HashSet<Task<(string Value, int ToNodeId)>> regionTasks =
  new HashSet<Task<(string Value, int ToNodeId)>>();
foreach (Connection connection in Connections[RegionName])
{
    regionTasks.Add(Task.Run(async () =>
    {        
        string value = await connection.GetValueAsync(Key);
        return (value, connection.ToNode.Id);
    }));
}

It is far more clear how it works and the 7 characters you saved in not typing Task.Run means you don't have to write a 50+ character comment explaining why something that looks like a delegate can be assigned to a variable of type Task

I'd say the C# compiler was saving you from writing bad code here, and it's another case of the VB compiler letting developers play fast an loose and writing hard to understand code

8 Comments

Upvoted. It should be noted though that the OP could have valid reasons to avoid the Task.Run. For example they could manipulate UI-elements inside the lambda, and so staying in the current synchronization context could be desirable.
Wrapping asynchronous operation with Task.Run would be a resource waste. Based on the name connection.GetValueAsync method accessing external resources. So i would say code Task.Run(async () => ...) is a code smell
Task.Run is intended for CPU-bound work. My code is very much I/O bound- waiting for HTTP responses. learn.microsoft.com/en-us/dotnet/csharp/programming-guide/….
@CaiusJard. I get what you're saying. You are correct that my technique of explicitly declaring a Func, then invoking it in the next line works. Though I think you included the wrong code in your "you'll note that this form works..." comment. I think you're too harsh calling my initial attempt code golf. I believe it's in the spirit of anonymous functions, which are intended to reduce code ceremony. I'm just trying to understand why the C# compiler doesn't understand my code. I find it ironic the VB.NET compiler does, considering VB tends to force excessively verbose code.
Thanks @TheodorZoulias. Stephen Toub definitely is an expert.
|
1

An easy way to invoke asynchronous lambdas in order to get the materialized tasks, is to use a helper function like the Run below:

public static Task Run(Func<Task> action) => action();
public static Task<TResult> Run<TResult>(Func<Task<TResult>> action) => action();

Usage example:

regionTasks.Add(Run(async () =>
{
    string value = await connection.GetValueAsync(Key);
    return (value, connection.ToNode.Id);
}));

The Run is similar with the Task.Run, with the difference that the action is invoked synchronously on the current thread, instead of being offloaded to the ThreadPool. Another difference is that an exception thrown directly by the action will be rethrown synchronously, instead of being wrapped in the resulting Task. It is assumed that the action will be an inline async lambda, as in the above usage example, which does this wrapping anyway, so adding another wrapper would be overkill. In case you want to eliminate this difference, and make it more similar with the Task.Run, you could use the Task constructor, and the RunSynchronously and Unwrap methods, as shown below:

public static Task Run(Func<Task> action)
{
    Task<Task> taskTask = new(action, TaskCreationOptions.DenyChildAttach);
    taskTask.RunSynchronously(TaskScheduler.Default);
    return taskTask.Unwrap();
}
public static Task<TResult> Run<TResult>(Func<Task<TResult>> action)
{
    Task<Task<TResult>> taskTask = new(action, TaskCreationOptions.DenyChildAttach);
    taskTask.RunSynchronously(TaskScheduler.Default);
    return taskTask.Unwrap();
}

3 Comments

This is very clean. I like it. I'm curious, did you write these helper methods because you've run into this issue in your own code? Or was it more a matter of the root cause being clear (at this point with all the sample code and commentary) and you thought to simply overcome the compiler's shortcomings via a helper method?
@ErikMadsen the later. :-) Actually I had the need to materialize lambdas in many occasions, and never occurred to me to use a generic Materialize method like the one above. I always settled with using a local function, or Task.Run, or whatever could do the job in the case at hand.
Yeah, perhaps I should get over my hangup with local functions or explicitly declaring a Func then invoking it immediately- and accept them as reasonable techniques. It comes down to a developer's preferred style, really.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.