How to do it...

  1. Start by adding the following variables to your form.
        double timerTtl = 10.0D;
private DateTime timeToLive;
private int cacheValue;
  1. In the form load event, set the label with the timer text. 
Strictly speaking, this is all just fluff. It's not really necessary when it comes to illustrating generalized async return types, but it helps us to visualize and understand the concept.
        private void Form1_Load(object sender, EventArgs e)
{
lblTimer.Text = $"Timer TTL {timerTtl} sec (Stopped)";
}
  1. Set the timer interval on the designer to 1000 ms and add the following code to the timer1_Tick event.
        private void timer1_Tick(object sender, EventArgs e)
{
if (timerTtl == 0)
{
timerTtl = 5;
}
else
{
timerTtl -= 1;
}
lblTimer.Text = $"Timer TTL {timerTtl} sec (Running)";
}
  1. Now create a method that simulates some sort of longer running task. Delay this for a second. Use the Random keyword to generate a random number and assign it to the cacheValue variable. Set the time to live, start the timer, and return the cached value to the calling code.
        public async Task<int> GetValue()
{
await Task.Delay(1000);

Random r = new Random();
cacheValue = r.Next();
timeToLive = DateTime.Now.AddSeconds(timerTtl);
timer1.Start();
return cacheValue;
}
  1. In the calling code, check to see if the time to live is still valid for the current cached value. If the time to live has expired, run the code that allocates and returns a Task<T> to get and set the cached value. If the time to live is still valid, just return the cached integer value.
You will notice that I am passing a Boolean out variable to indicate that a cached value has been read or set.
        public ValueTask<int> LoadReadCache(out bool blnCached)
{
if (timeToLive < DateTime.Now)
{
blnCached = false;
return new ValueTask<int>(GetValue());
}
else
{
blnCached = true;
return new ValueTask<int>(cacheValue);
}
}
  1. The code for the button click uses the out variable isCachedValue and sets the text in the textbox accordingly.
        private async void btnTestAsync_Click(object sender, EventArgs e)
{
int iVal = await LoadReadCache(out bool isCachedValue);
if (isCachedValue)
txtOutput.Text = $"Cached value {iVal} read";
else
txtOutput.Text = $"New value {iVal} read";
}
  1. When you finish adding all the code, run your application and click on the Test async button. This will read a new value from the GetValue() method, cache it, and start the time to live count down.
  1. If you click on the button again before the time to live has expired, the cached value is returned.
  1. When the time to live expires, clicking on the Test async button will call the GetValue() method again and the process repeats.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.47.218