c# .net why does Task.Run seem to handle Func differently than other code?

前端 未结 6 1467
生来不讨喜
生来不讨喜 2021-01-01 16:07

The new Task.Run static method that\'s part of .NET 4.5 doesn\'t seem to behave as one might expect.

For example:

Task t = Task.Run(()=&         


        
6条回答
  •  梦毁少年i
    2021-01-01 16:36

    This was supposed to be fixed in .Net 4.0, but Task.Run() is new to .Net 4.5

    .NET 4.5 has its own overload ambiguity by adding the Task.Run(Func>) method. And the support for async/await in C# version 5. Which permits an implicit conversion from T foo() to Func>.

    That's syntax sugar that's pretty sweet for async/await but produces cavities here. The omission of the async keyword on the method declaration is not considered in the method overload selection, that opens another pandora box of misery with programmers forgetting to use async when they meant to. Otherwise follows the usual C# convention that only the method name and arguments in the method signature is considered for method overload selection.

    Using the delegate type explicitly is required to resolve the ambiguity.

提交回复
热议问题