在下面的代码中,由于接口的原因,该类LazyBar必须从其方法中返回一个任务(并且为了参数,不能更改)。如果LazyBars 的实现不寻常,因为它碰巧快速同步地运行 - 从该方法返回 No-Operation 任务的最佳方式是什么?
LazyBar
我已经在Task.Delay(0)下面进行了,但是我想知道如果函数被 大量 调用(为了论证,每秒数百次),这是否有任何性能副作用:
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(); } } }
今天,我建议使用Task.CompletedTask来完成此任务。
.net 4.6 之前:
使用Task.FromResult(0)or将比使用无操作表达式Task.FromResult<object>(null)创建更少的开销。Task在创建Task具有预定结果的结果时,不涉及调度开销。
Task.FromResult(0)
Task.FromResult<object>(null)
Task