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

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.
主站蜘蛛池模板: 乐陵市| 抚州市| 陇南市| 永善县| 铜鼓县| 闽清县| 千阳县| 夏邑县| 隆尧县| 枝江市| 崇信县| 贵德县| 牡丹江市| 岳阳市| 富源县| 德令哈市| 中超| 信丰县| 上林县| 重庆市| 交城县| 江源县| 陈巴尔虎旗| 海林市| 康定县| 宜阳县| 南阳市| 邳州市| 东海县| 昌平区| 白河县| 莱州市| 通榆县| 澄迈县| 东光县| 赣州市| 马公市| 汕尾市| 鄂尔多斯市| 昭通市| 延庆县|