在下面的代码,由于接口,类LazyBar
必须从它的方法(和为了讨论不能改变)返回的任务。 如果LazyBar
的实现是不寻常的,因为它发生在快速同步运行-什么是从方法返回一个空操作任务的最佳方法是什么?
我已经与Task.Delay(0)
以下,但是我想知道这是否有任何性能的副作用,如果函数被调用了很多 (为了讨论各种情形,说上百次),:
- 这是否语法糖未风大的东西?
- 是否开始堵塞我的应用程序的线程池?
- 是编译器菜刀足以应对
Delay(0)
不同? - 将
return 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();
}
}
}