LazyBar
必须从其方法返回任务(出于论证目的不能更改)。如果LazyBar
的实现不同寻常,它可以快速且同步运行 - 那么从该方法返回无操作任务的最佳方法是什么?我选择了下面的
Task.Delay(0)
,但我想知道如果函数被频繁调用(为论证目的,假设每秒调用数百次),是否会有任何性能副作用:- 这种语法糖是否会展开为较大的东西? - 它会开始堵塞我的应用程序线程池吗? - 编译器是否足够聪明以不同方式处理
Delay(0)
?
- 返回 Task.Run(() => { });
是否会有任何不同?还有更好的方法吗?
using System.Threading.Tasks;
namespace MyAsyncTest
{
internal interface IFooFace
{
Task WillBeLongRunningAsyncInTheMajorityOfImplementations();
}
/// <summary>
/// An implementation, that unlike most cases, will not have a long-running
/// operation in 'WillBeLongRunningAsyncInTheMajorityOfImplementations'
/// </summary>
internal class LazyBar : IFooFace
{
#region IFooFace Members
public Task WillBeLongRunningAsyncInTheMajorityOfImplementations()
{
// First, do something really quick
var x = 1;
// Can't return 'null' here! Does 'Task.Delay(0)' have any performance considerations?
// Is it a real no-op, or if I call this a lot, will it adversely affect the
// underlying thread-pool? Better way?
return Task.Delay(0);
// Any different?
// return Task.Run(() => { });
// If my task returned something, I would do:
// return Task.FromResult<int>(12345);
}
#endregion
}
internal class Program
{
private static void Main(string[] args)
{
Test();
}
private static async void Test()
{
IFooFace foo = FactoryCreate();
await foo.WillBeLongRunningAsyncInTheMajorityOfImplementations();
return;
}
private static IFooFace FactoryCreate()
{
return new LazyBar();
}
}
}
Task.FromResult<object>(null)
。 - CodesInChaos