简体   繁体   English

当等待空任务时方法“做”是什么?

[英]What does a method “do” when it awaits an empty Task?

I am outlining a class and to keep myself happy I have made a temporary return for a method 我正在概述一个课程,为了让自己高兴,我已经为一个方法做了一个临时的回报

public override Task DoPostProcessing()
{
    return Task.Factory.StartNew(() => { ;} );
}

If I were to call this method and await it, what "happens"? 如果我打电话给这个方法并await它,会发生什么? Is this Task optimized away at compile time or is it ran? Task是在编译时优化还是运行?

It is run. 它运行。 It will schedule a method on a thread pool that just returns immediately. 它将在线程池上安排一个方法,该方法只是立即返回。

On a side note, do not use StartNew ; 另外, 请不要使用StartNew ; it is dangerous . 这很危险 Use Task.Run to run code on a thread pool thread, or just use Task.FromResult to return an already-completed task. 使用Task.Run在线程池线程上运行代码,或者只使用Task.FromResult返回已完成的任务。 Task.FromResult should be your go-to choice for noop implementations. Task.FromResult应该是noop实现的首选。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么Task.Run(()=&gt; something)调用等待死锁的同步方法? - Why does Task.Run(() => something) that calls a sync method that awaits deadlock? 什么时候有多个等待有意义? - When do multiple awaits make sense? 如果在一个不依赖于彼此的方法中有多个等待,异步等待如何工作? - How does async await work when if there are multiple awaits in a method which aren't dependent on eachother? 当线程“唤醒”某物时会发生什么 - What happens to a thread when it 'awaits' something 许多等待Async方法,或者一次等待包装Task.Run? - Many awaits for Async method, or a single await for a wrapping Task.Run? 方法返回TaskCompletionSource的含义是什么 <bool> 变量? - What does it mean when a method returns .Task for a TaskCompletionSource<bool> variable? Windows Phone CreateFolderAsync方法在等待时给出错误 - Windows Phone CreateFolderAsync method is giving error when it awaits 单个方法中的多个等待 - Multiple Awaits in a single method 当一个方法仅在return语句中等待时,标记一个异步是否有用? - Is it useful to mark a method async when it only awaits at the return statement? forceRefresh 参数在只调用 await Task.FromResult(items) 的方法中有什么作用? - What does the forceRefresh parameter do in a method that only calls await Task.FromResult(items)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM