在下面的代码中,由于接口的原因,类LazyBar必须从它的方法返回一个任务(出于参数的考虑,不能更改)。如果LazyBars的实现是不寻常的,因为它恰好快速和同步地运行——从方法中返回一个No-Operation任务的最佳方法是什么?
我已经使用下面的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();
}
}
}