官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 天水市| 济宁市| 葫芦岛市| 西昌市| 万源市| 永州市| 临颍县| 额济纳旗| 红桥区| 申扎县| 盐源县| 柘荣县| 东丽区| 商城县| 台东市| 稻城县| 古浪县| 海伦市| 三台县| 海晏县| 青冈县| 华容县| 密云县| 张家港市| 兴山县| 德化县| 马尔康县| 城市| 酒泉市| 柞水县| 榆中县| 台前县| 班戈县| 大埔区| 宁明县| 东兴市| 鄂州市| 临江市| 宁强县| 濉溪县| 同江市|