Created
May 11, 2018 10:02
-
-
Save revocengiz/f748cf82a29e7d03457b74757b2e309d to your computer and use it in GitHub Desktop.
GetCustomerById by ValueTask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Özellikle cachlenen verinin dönüldüğü yerlerde çoğu zaman method sync çalışacağı için | |
// Task<T> yerine ValueTask<T> dönmek daha performanslı olacaktır (daha az allocation) | |
// Ancak bu method TPL'deki Task.WhenAll veya Task.WhenAny ile kullanıldığı zaman | |
// ValueTask<T> Task<T>'ye dönüştürüleceği için daha çok allocation sebep olabilir | |
// http://blog.i3arnon.com/2015/11/30/valuetask/ | |
// https://www.productivecsharp.com/2017/07/practical-csharp-generalized-async-return-types/ | |
// “ValueTask<T> is a discriminated union of a T and a Task<T>, making it allocation-free | |
// for ReadAsync<T> to synchronously return a T value it has available (in contrast to using Task.FromResult<T>, | |
// // which needs to allocate a Task<T> instance). | |
// ValueTask<T> is awaitable, so most consumption of instances will be indistinguishable from with a Task<T>.” | |
public ValueTask<CustomerModel> GetCustomerById(long customerId, IdentityAuthentication.Models.UserModel user) | |
{ | |
string key = $"customer:{customerId}"; | |
var data = _memory.Get<CustomerModel>(key); | |
return data != null ? new ValueTask<CustomerModel>(data) : new ValueTask<CustomerModel>(GetCustomerInternal()); | |
async Task<CustomerModel> GetCustomerInternal() | |
{ | |
var response = await _coreHttpService.HttpRequest($"v1/customer/getbycustomerid/{customerId}", HttpMethod.Get, user, null); | |
if (response.IsSuccessStatusCode) | |
{ | |
data = JsonConvert.DeserializeObject<CustomerModel>(await response.Content.ReadAsStringAsync()); | |
_memory.Set(key, data, TimeSpan.FromMinutes(cacheTimeSpanMinute)); | |
} | |
return data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment