From 36a6f0e77c06214108da3804ed14dde442cd7c91 Mon Sep 17 00:00:00 2001 From: Murat Cakir Date: Wed, 28 Sep 2022 21:43:15 +0200 Subject: [PATCH] ApiUserStore uses PortableTimer now --- .../Services/ApiUserStore.cs | 39 ++++++++++++------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/src/Smartstore.Modules/Smartstore.WebApi/Services/ApiUserStore.cs b/src/Smartstore.Modules/Smartstore.WebApi/Services/ApiUserStore.cs index b78258088f..611081296f 100644 --- a/src/Smartstore.Modules/Smartstore.WebApi/Services/ApiUserStore.cs +++ b/src/Smartstore.Modules/Smartstore.WebApi/Services/ApiUserStore.cs @@ -1,9 +1,6 @@ -using System.Threading; -using Autofac; +using Autofac; using Microsoft.Extensions.Caching.Memory; -using Microsoft.Extensions.DependencyInjection; -using Smartstore.Data; -using Smartstore.Utilities; +using Smartstore.Threading; using Smartstore.Web.Api.Models; namespace Smartstore.Web.Api @@ -20,7 +17,7 @@ public class ApiUserStore : Disposable, IApiUserStore private readonly IDbContextFactory _dbContextFactory; private readonly IMemoryCache _memCache; - private Timer _timer; + private PortableTimer _timer; private DateTime _lastSavingDate = DateTime.UtcNow; public ApiUserStore(IDbContextFactory dbContextFactory, IMemoryCache memCache) @@ -33,14 +30,19 @@ public void Activate(TimeSpan storingInterval) { _lastSavingDate = DateTime.UtcNow; - _timer ??= new(async state => + if (_timer == null) { - if (_memCache.TryGetValue(WebApiService.UsersKey, out object cachedUsers)) - { - await SaveApiUsersInternal(cachedUsers as Dictionary, true); - } - }, - null, storingInterval, storingInterval); + _timer ??= new(_ => OnTick()); + _timer.Start(storingInterval); + } + } + + private async Task OnTick() + { + if (_memCache.TryGetValue(WebApiService.UsersKey, out object cachedUsers)) + { + await SaveApiUsersInternal(cachedUsers as Dictionary, true); + } } public Task SaveApiUsersAsync(Dictionary users) @@ -95,6 +97,17 @@ protected override void OnDispose(bool disposing) _timer?.Dispose(); } } + + protected override async ValueTask OnDisposeAsync(bool disposing) + { + if (disposing) + { + _timer?.Dispose(); + + // Persist remaining data on dispose. + await OnTick(); + } + } }