- Mastering Visual Studio 2017
- Kunal Chowdhury
- 206字
- 2021-07-15 17:26:39
Uses of the generalized async return types
Prior to C# 7.0, async methods had to return either void, Task, or Task<T>. As Task is a reference type, returning such an object from async methods can impact performance because it allocates an object into memory even though it returns a cached object or runs asynchronously.
To overcome this, C# 7.0 introduces the ValueTask type, which is set to prevent the allocation of a Task<T> object when the result of the async operation is already available. Using it, the async methods can return types other than Task, Task<T>, and void:
public async ValueTask<long> GetValue() { return await Task.Run<long>(() => 5000); }
If you receive an error accessing ValueTask in C# 7.0, you must explicitly reference System.Threading.Tasks.Extensions from the NuGet package library. To install the package, either open the NuGet package manager or the NuGet package manager console; or you can simply click the Install package 'System.Threading.Tasks.Extensions' menu item from the tooltip, as shown in the following screenshot. This is the simplest way to download and install the package:

Alternatively, you can find the package here: http://www.nuget.org/packages/System.Threading.Tasks.Extensions/.
Once you have installed the package, you can see that the DLL reference to System.Threading.Tasks.Extensions has already been added to your project:

- Unity 2020 Mobile Game Development
- 云原生Spring實(shí)戰(zhàn)
- Raspberry Pi 2 Server Essentials
- 大學(xué)計(jì)算機(jī)基礎(chǔ)(第2版)(微課版)
- Unity Game Development Scripting
- D3.js 4.x Data Visualization(Third Edition)
- Asynchronous Android Programming(Second Edition)
- Windows內(nèi)核編程
- Kotlin開(kāi)發(fā)教程(全2冊(cè))
- Java Web應(yīng)用開(kāi)發(fā)給力起飛
- Flink技術(shù)內(nèi)幕:架構(gòu)設(shè)計(jì)與實(shí)現(xiàn)原理
- OpenCV Android Programming By Example
- Getting Started with JUCE
- JavaWeb從入門(mén)到精通(視頻實(shí)戰(zhàn)版)
- Design Patterns and Best Practices in Java