- 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:

- 計算思維與算法入門
- Java程序設(shè)計與開發(fā)
- 從零開始:數(shù)字圖像處理的編程基礎(chǔ)與應(yīng)用
- JavaScript高效圖形編程
- jQuery從入門到精通 (軟件開發(fā)視頻大講堂)
- 編程數(shù)學(xué)
- Mastering HTML5 Forms
- 深度實踐KVM:核心技術(shù)、管理運(yùn)維、性能優(yōu)化與項目實施
- Julia High Performance(Second Edition)
- SEO教程:搜索引擎優(yōu)化入門與進(jìn)階(第3版)
- Python應(yīng)用與實戰(zhàn)
- Mastering Bootstrap 4
- 企業(yè)級Java現(xiàn)代化:寫給開發(fā)者的云原生簡明指南
- Access 2016數(shù)據(jù)庫應(yīng)用與開發(fā):實戰(zhàn)從入門到精通(視頻教學(xué)版)
- SQL Server 2012數(shù)據(jù)庫管理與開發(fā)(慕課版)