public void Register(RconModel rconModel) { _rconModel = rconModel; _nLogListener = new NLogListener(); _nLogListener.LogWrite += NLogListenerOnLogWrite; _cancellationTokenSource = new CancellationTokenSource(); _logWriteTimerTask = PeriodicTaskFactory.Start( () => { ProcessQueue(); }, intervalInMilliseconds: _LogWriteFlushTimeMs, delayInMilliseconds: 1000, duration: -1, maxIterations: -1, synchronous: false, cancelToken: _cancellationTokenSource.Token, periodicTaskCreationOptions: TaskCreationOptions.None); //// Repeat every 1 second //_logWriteTimerAction = ignored1 => // { // if (ignored1.IsCompleted) // return; // FlushBuffer(); // //Task.Delay(_LogWriteFlushTimeMs, _cancellationTokenSource.Token).ContinueWith(ignored2 => _logWriteTimerAction(ignored2), _cancellationTokenSource.Token); // _logWriteTimerTask = Task.Delay(_LogWriteFlushTimeMs, _cancellationTokenSource.Token).ContinueWith(_logWriteTimerAction, _cancellationTokenSource.Token); // }; //// Wait 1 sec, then start above repeating task //_logWriteTimerTask = Task.Delay(1000, _cancellationTokenSource.Token).ContinueWith(_logWriteTimerAction, _cancellationTokenSource.Token); }
private void WriteSequencesPeriodically(MemoryMappedViewAccessor accessor, List <T> sequences) { foreach (var sequence in sequences) { _entityListToWrite.Enqueue(sequence); } if (_stateTimer != null) { _stateTimer.CancelToken = new CancellationToken(true); } _stateTimer = new PeriodicTaskFactory((task) => { lock (sync) { // var isOwnedMutex = LockKeyData.WaitOne(); LockKeyData.WaitOne(); WriteSequences(accessor); // if (isOwnedMutex) LockKeyData.ReleaseMutex(); } }, new TimeSpan(0, 0, 2), new TimeSpan(0, 0, 2)); _stateTimer.Start(); }
protected override void OnStart(string[] args) { _initializationCancelTokenSource = new CancellationTokenSource(); _intitializationCancellationToken = _initializationCancelTokenSource.Token; _initializationTask = Task.Run(() => { //Kick off polling from here that also uses _intitializationCancellationToken, so that when _initializationCancelTokenSource.Cancel() is invoked from OnStop it will start cancellation chain reaction to stop all running activity. You can pass it even into your methods and check _intitializationCancellationToken.IsCancellationRequested and take appropriate actions. //using the Task timer from the other stack overflow post, You could do something like Task perdiodicTask = PeriodicTaskFactory.Start(() => { Console.WriteLine(DateTime.Now); //execute your logic here that has to run periodically }, intervalInMilliseconds: 5000, // fire every 5 seconds... cancelToken: _intitializationCancellationToken); // Using same cancellation token to manage timer cancellation perdiodicTask.ContinueWith(_ => { Console.WriteLine("Finished!"); }).Wait(); }, _intitializationCancellationToken) .ContinueWith(t => { //deal with any task related errors }, TaskContinuationOptions.OnlyOnFaulted); }
private void RecalculateProductionTimer() { _registryGroupState.Round = 0; if (_syncCycleDescriptor != null) { _syncCycleDescriptor.CancellationTokenSource.Cancel(); _syncCycleDescriptor.CancellationRequested = true; } _syncCycleDescriptor = new SyncCycleDescriptor(_synchronizationContext.LastBlockDescriptor); PeriodicTaskFactory.Start(o => { SyncCycleDescriptor syncCycleDescriptor = (SyncCycleDescriptor)o; SortedList <ushort, RegistryRegisterBlock> transactionStateWitnesses = _registryMemPool.DequeueStateWitnessBulk(); SortedList <ushort, RegistryRegisterUtxoConfidential> transactionUtxoWitnesses = _registryMemPool.DequeueUtxoWitnessBulk(); RegistryFullBlock registryFullBlock = ProduceTransactionsFullBlock(transactionStateWitnesses, transactionUtxoWitnesses, syncCycleDescriptor.SynchronizationDescriptor, syncCycleDescriptor.Round); RegistryShortBlock registryShortBlock = ProduceTransactionsShortBlock(registryFullBlock); SendTransactionsBlocks(registryFullBlock, registryShortBlock); syncCycleDescriptor.Round++; if (syncCycleDescriptor.CancellationRequested) { syncCycleDescriptor.CancellationTokenSource.Cancel(); } }, _syncCycleDescriptor, _registrationPeriodMsec * _registryConfiguration.TotalNodes, _registryConfiguration.Position * _registrationPeriodMsec, cancelToken: _syncCycleDescriptor.CancellationTokenSource.Token, periodicTaskCreationOptions: TaskCreationOptions.LongRunning); }
public void Start() { //Delay first execution until expected time has passed _wrappedAdapter.TaskDelay(_interval * 1000).Wait(); var schedulerTask = PeriodicTaskFactory.Start(() => AddSegmentsToQueue(), intervalInMilliseconds: _interval * 1000, cancelToken: _cancelTokenSource.Token); }
public void Start() { ThreadUtils.Delay(firstPushWindow * 1000).ContinueWith((t) => { SendBulkEvents(); PeriodicTaskFactory.Start(() => { SendBulkEvents(); }, interval * 1000, cancellationTokenSource.Token); }); }
public async Task <bool> AnswerQuestionTimer(long questionid) { var userId = _securityContext.User.Id; var counter = 1; Task perdiodicTask = PeriodicTaskFactory.Start(() => { Console.WriteLine($"===========================Begin({counter})========================="); //_hubContext.Clients.User(userId.ToString()).SendAsync("ReceiveMessagePrivate", $"{counter}: {DateTime.Now}"); _hubContext.Clients.User(userId.ToString()).SendAsync("ReceiveMessagePrivate", JsonConvert.SerializeObject(new SocketObject() { Timestamp = GlobalSettings.CURRENT_DATETIME_AS_STRING, Object = new { Counter = counter }, Message = "Tick" })); counter++; }, intervalInMilliseconds: 1000, // fire every one seconds.. maxIterations: 20, periodicTaskCreationOptions: TaskCreationOptions.RunContinuationsAsynchronously); // for a total of 20 iterations... await perdiodicTask.ContinueWith(_ => { Console.WriteLine("===========================End========================="); _competitionQueryProcessor.AnswerQuestion(questionid, 0, userId); //_hubContext.Clients.User(userId.ToString()).SendAsync("ReceiveMessagePrivate", $"User did't answer, result is 0 {DateTime.Now}"); _hubContext.Clients.User(userId.ToString()).SendAsync("ReceiveMessagePrivate", JsonConvert.SerializeObject(new SocketObject() { Timestamp = GlobalSettings.CURRENT_DATETIME_AS_STRING, Object = new { Result = 0 }, Message = "User did't answer" })); }); return(true); }
public static void OnRepositoryCacheConfig(Type dBContext) { Core.Cmn.AppBase.DependencyInjectionFactory.CreateInjectionInstance <ICheckSqlServiceBrockerRepository>().CheckServiceBrokerOnDb(); var repositoryAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(ass => ass.FullName.ToLower().Contains(".rep")).ToList(); bool isNeedCache; if (Core.Cmn.ConfigHelper.TryGetConfigValue <bool>("IsNeedCache", out isNeedCache) && !isNeedCache) { repositoryAssemblies = repositoryAssemblies.Where(ass => ass.FullName.ToLower().Contains("core.rep")).ToList(); } // Core.Rep must build it's cache at first of all. var coreRepAssembly = repositoryAssemblies.FirstOrDefault(ass => ass.FullName.ToLower().Contains("core.rep")); if (repositoryAssemblies != null) { repositoryAssemblies.Remove(coreRepAssembly); BuildCachesInAssembly(dBContext, coreRepAssembly, true); } repositoryAssemblies.ForEach(ass => BuildCachesInAssembly(dBContext, ass, true)); PeriodicTaskFactory p = new PeriodicTaskFactory((pt) => { CacheConfig.CacheManagementRepository.Delete(); }, new TimeSpan(0, 0, 1200), new TimeSpan(0, 0, 1200)); p.Start(); if (Core.Cmn.ConfigHelper.GetConfigValue <bool>("EnableCacheServerListener") && !IsCacheServerServiceStart) { StartCacheServerService(); } }
public void Start() { Task periodicTask = PeriodicTaskFactory.Start(() => { RefreshSplits(); }, intervalInMilliseconds: interval * 1000, cancelToken: cancelTokenSource.Token); }
public void Start() { _wrapperAdapter .TaskDelay(_firstPushWindow * 1000) .ContinueWith((t) => { SendBulkEvents(); PeriodicTaskFactory.Start(() => { SendBulkEvents(); }, _interval * 1000, _cancellationTokenSource.Token); }); }
public void Start() { var periodicTask = PeriodicTaskFactory.Start(async() => { await FetchSplits(); }, intervalInMilliseconds: _interval * 1000, cancelToken: _cancelTokenSource.Token); }
public void StartScheduler() { //Delay first execution until expected time has passed Task.Delay(interval * 1000).Wait(); Task schedulerTask = PeriodicTaskFactory.Start( () => AddSegmentsToQueue(), intervalInMilliseconds: interval * 1000, cancelToken: cancelTokenSource.Token); }
private void MonitorJobStatus(Action job, string id, CancellationToken token) { var monitor = PeriodicTaskFactory.Start(job, intervalInMilliseconds: 2000, duration: 60000 * 60, // wait for max. 1 hour until abort cancelToken: token); monitor.ContinueWith(_ => { JobCompletedEvent?.Invoke(id); }); }
protected async Task PeriodicTaskFactoryCore() { int expectedChickenNumber = 2; int actualChickenNumber = 0; await PeriodicTaskFactory.Start( () => { actualChickenNumber = IncrementChickenNumber(actualChickenNumber); }, MockData.RepeatIntervalInMillisecs, MockData.StartDelayInMillisecs, MockData.Duration, expectedChickenNumber).ConfigureAwait(false); Assert.Equal(expectedChickenNumber, actualChickenNumber); }
public void Initialize() { if (IsInitialized) { return; } _dataContext = new DataContext(_configurationService.Get <ISQLiteConfiguration>()); _dataContext.ChangeTracker.StateChanged += (s, e) => { AccountIdentity accountIdentity = e.Entry.Entity as AccountIdentity; }; _dataContext.Database.EnsureCreated(); _dataContext.EnsureConfigurationCompleted(); PeriodicTaskFactory.Start(() => { if (_isSaving) { return; } lock (_sync) { if (_isSaving) { return; } _isSaving = true; try { if (_dataContext.ChangeTracker.HasChanges()) { _dataContext.SaveChanges(); } } catch (Exception ex) { _logger.Error("Failure during saving data to database", ex); } finally { _isSaving = false; } } }, 1000, cancelToken: _cancellationTokenSource.Token, periodicTaskCreationOptions: System.Threading.Tasks.TaskCreationOptions.LongRunning); IsInitialized = true; }
private void SynchronizationStateChanged(string propName) { _cancellationTokenSource?.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); PeriodicTaskFactory.Start(() => { IEnumerable <RegistryFullBlock> registryFullBlocks = _syncRegistryMemPool.GetRegistryBlocks(); CreateAndDistributeCombinedBlock(registryFullBlocks); DistributeAndSaveFullBlock(registryFullBlocks); }, _cyclePeriodMsec * _synchronizationConfiguration.TotalNodes, _cyclePeriodMsec * _synchronizationConfiguration.Position, cancelToken: _cancellationTokenSource.Token, periodicTaskCreationOptions: TaskCreationOptions.LongRunning); }
private void ScheduleMaxTimeNoTestConReceivedFuture() { if (maxTimeNoTestConReceivedFuture != null) { maxTimeNoTestConReceivedFuture.Cancel(); maxTimeNoTestConReceivedFuture = null; } maxTimeNoTestConReceivedFuture = PeriodicTaskFactory.Start(() => { Close(); ConnectionClosed?.Invoke(new IOException( "The maximum time that no test frame confirmation was received (t1) has been exceeded. t1 = " + settings.MaxTimeNoAckReceived + "ms")); }, settings.MaxTimeNoAckReceived); }
public void Initialize() { if (IsInitialized) { return; } _dataContext.Database.EnsureCreated(); _dataContext.EnsureConfigurationCompleted(); PeriodicTaskFactory.Start(() => { if (_isSaving) { return; } lock (_sync) { if (_isSaving) { return; } _isSaving = true; try { if (_dataContext.ChangeTracker.HasChanges()) { _dataContext.SaveChanges(); } } catch (Exception ex) { _logger.Error("Failure during saving data to database", ex); } finally { _isSaving = false; } } }, 1000, cancelToken: _cancellationTokenSource.Token); IsInitialized = true; }
public void Start() { Task.Factory.StartNew(() => { while (true) { if (_gates.IsSDKReady(0)) { //Delay first execution until expected time has passed var intervalInMilliseconds = _interval * 1000; _wrappedAdapter.TaskDelay(intervalInMilliseconds).Wait(); PeriodicTaskFactory.Start(() => AddSegmentsToQueue(), intervalInMilliseconds, _cancelTokenSource.Token); break; } _wrappedAdapter.TaskDelay(500).Wait(); } }); }
public void Send() { Task perdiodicTask = PeriodicTaskFactory.Start(() => { // Console.WriteLine(DateTime.Now); List <FlyModel> bjModelTemp = new List <FlyModel>(); List <FlyModel> shModelTemp = new List <FlyModel>(); List <FlyModel> gzModelTemp = new List <FlyModel>(); GetData(ref bjModelTemp, ref shModelTemp, ref gzModelTemp); Clients.All.getFlyMsgSend(bjModelTemp, shModelTemp, gzModelTemp); }, intervalInMilliseconds: 5000// fire every two seconds... ); //List<FlyModel> bjModelTemp = new List<FlyModel>(); //List<FlyModel> shModelTemp = new List<FlyModel>(); //List<FlyModel> gzModelTemp = new List<FlyModel>(); //GetData(ref bjModelTemp, ref shModelTemp, ref gzModelTemp); //Clients.All.getFlyMsgSend(bjModelTemp, shModelTemp, gzModelTemp); }
public async Task <bool> GetCurrentUser() { var userId = _context.User.Id.ToString(); var counter = 1; Task perdiodicTask = PeriodicTaskFactory.Start(() => { Console.WriteLine($"===========================Begin({counter})========================="); _hubContext.Clients.User(userId).SendAsync("ReceiveMessagePrivate", $"{counter}: {DateTime.Now}"); counter++; }, intervalInMilliseconds: 1000, // fire every one seconds.. maxIterations: 10, periodicTaskCreationOptions: TaskCreationOptions.RunContinuationsAsynchronously); // for a total of 20 iterations... await perdiodicTask.ContinueWith(_ => { Console.WriteLine("===========================End========================="); _hubContext.Clients.User(userId).SendAsync("ReceiveMessagePrivate", $"ENDDDDDDDDD: {DateTime.Now}"); }); return(true); }
private void cmbAutoRefrsh_SelectionChanged(object sender, SelectionChangedEventArgs e) { var delay = (int)cmbAutoRefrsh.SelectedValue; if (_stateTimer != null) { _stateTimer.CancelToken = new CancellationToken(true); } if (delay > 0) { _stateTimer = new PeriodicTaskFactory((task) => { //var dataSource = _viewer.GetEventLogData(); this.Dispatcher.BeginInvoke(new Action(InsertNewDataToGrid)); }, new TimeSpan(0, 0, delay), new TimeSpan(0, 0, delay)); _stateTimer.Start(); } }
private void ResetMaxIdleTimeTimer() { if (maxIdleTimeTimerFuture != null) { maxIdleTimeTimerFuture.Cancel(); maxIdleTimeTimerFuture = null; } maxIdleTimeTimerFuture = PeriodicTaskFactory.Start(() => { try { writer.Write(TestfrActBuffer, 0, TestfrActBuffer.Length); writer.Flush(); } catch (Exception) { // ignored } ScheduleMaxTimeNoTestConReceivedFuture(); }, settings.MaxIdleTime); }
public void Start() { _logger.Info("Started"); _communicationService.Start(); PeriodicTaskFactory.Start(async() => { if (_isProcessing) { return; } lock (_sync) { if (_isProcessing) { return; } _isProcessing = true; } try { Proto.Model.SyncBlockDescriptor syncBlockDescriptor = _syncLayerSyncManagerClient.GetLastSyncBlock(new Empty()); if (_lastSyncDescriptor.Height < syncBlockDescriptor.Height) { _lastSyncDescriptor = new Entities.SyncBlockDescriptor(syncBlockDescriptor.Height, syncBlockDescriptor.Hash.ToByteArray()); _dataAccessService.UpdateLastSyncBlock(syncBlockDescriptor.Height, syncBlockDescriptor.Hash.ToByteArray()); } ulong lastCombinedBlockHeight = _lastCombinedBlockDescriptor.Height; SynchronizationRegistryCombinedBlock lastCombinedBlock = null; AsyncServerStreamingCall <TransactionInfo> asyncCall = _syncLayerSyncManagerClient.GetCombinedRegistryBlocksContentSinceHeight(new ByHeightRequest { Height = _lastCombinedBlockDescriptor.Height }); while (await asyncCall.ResponseStream.MoveNext(_cancellationToken)) { SynchronizationRegistryCombinedBlock combinedBlock = GetRegistryCombinedBlock(asyncCall.ResponseStream.Current); if (combinedBlock == null) { continue; } try { _dataAccessService.UpdateLastRegistryCombinedBlock(combinedBlock.BlockHeight, combinedBlock.RawData.ToArray()); if (lastCombinedBlockHeight < combinedBlock.BlockHeight) { lastCombinedBlockHeight = combinedBlock.BlockHeight; lastCombinedBlock = combinedBlock; } foreach (byte[] fullRegistryBlockHash in combinedBlock.BlockHashes) { await UpdateTransactionsByFullRegistryBlock(combinedBlock, fullRegistryBlockHash); } } catch (Exception ex) { _logger.Error($"Failure during obtaining transactions at Registry Combined Block with height {combinedBlock.BlockHeight}", ex); } } if (lastCombinedBlock != null) { _lastCombinedBlockDescriptor = new RegistryCombinedBlockDescriptor(lastCombinedBlock.BlockHeight, lastCombinedBlock.RawData.ToArray(), _defaultHashCalculation.CalculateHash(lastCombinedBlock.RawData)); _dataAccessService.UpdateLastRegistryCombinedBlock(_lastCombinedBlockDescriptor.Height, _lastCombinedBlockDescriptor.Hash); } } catch (Exception ex) { _logger.Error("Failure during updating blockchain", ex); } finally { _isProcessing = false; } }, 5000, cancelToken: _cancellationToken); }
public void Start() { PeriodicTaskFactory.Start(() => { SendBulkImpressions(); }, interval * 1000, cancellationTokenSource.Token); }
public override void Run() { try { var reader = innerConnection.reader; while (true) { if (reader.ReadByte() != 0x68) { throw new IOException("Message does not start with 0x68"); } var aPdu = new APdu(reader, innerConnection.settings); switch (aPdu.GetApciType()) { case APdu.ApciType.I_FORMAT: if (innerConnection.receiveSequenceNumber != aPdu.GetSendSeqNumber()) { throw new IOException("Got unexpected send sequence number: " + aPdu.GetSendSeqNumber() + ", expected: " + innerConnection.receiveSequenceNumber); } innerConnection.receiveSequenceNumber = (aPdu.GetSendSeqNumber() + 1) % 32768; innerConnection.HandleReceiveSequenceNumber(aPdu); innerConnection.NewASdu?.Invoke(aPdu.GetASdu()); var numUnconfirmedIPdusReceived = innerConnection.GetSequenceNumberDifference( innerConnection.receiveSequenceNumber, innerConnection.acknowledgedReceiveSequenceNumber); if (numUnconfirmedIPdusReceived > innerConnection.settings.MaxUnconfirmedIPdusReceived) { innerConnection.SendSFormatPdu(); if (innerConnection.maxTimeNoAckSentFuture != null) { innerConnection.maxTimeNoAckSentFuture.Cancel(); innerConnection.maxTimeNoAckSentFuture = null; } } else { if (innerConnection.maxTimeNoAckSentFuture == null) { innerConnection.maxTimeNoAckSentFuture = PeriodicTaskFactory.Start(() => { innerConnection.SendSFormatPdu(); innerConnection.maxTimeNoAckSentFuture = null; }, innerConnection.settings.MaxTimeNoAckSent); } } innerConnection.ResetMaxIdleTimeTimer(); break; case APdu.ApciType.STARTDT_CON: innerConnection.startdtConSignal?.CountDown(); innerConnection.ResetMaxIdleTimeTimer(); break; case APdu.ApciType.STARTDT_ACT: innerConnection.startdtactSignal?.CountDown(); break; case APdu.ApciType.S_FORMAT: innerConnection.HandleReceiveSequenceNumber(aPdu); innerConnection.ResetMaxIdleTimeTimer(); break; case APdu.ApciType.TESTFR_ACT: try { innerConnection.writer.Write(TestfrConBuffer, 0, TestfrConBuffer.Length); innerConnection.writer.Flush(); } catch (Exception e) { throw new IOException(e.Message); } innerConnection.ResetMaxIdleTimeTimer(); break; case APdu.ApciType.TESTFR_CON: if (innerConnection.maxTimeNoTestConReceivedFuture != null) { innerConnection.maxTimeNoTestConReceivedFuture.Cancel(); innerConnection.maxTimeNoTestConReceivedFuture = null; } innerConnection.ResetMaxIdleTimeTimer(); break; default: throw new IOException("Got unexpected message with APCI Type: " + aPdu.GetApciType()); } } } catch (IOException e) { innerConnection.closedIoException = e; } catch (Exception e) { innerConnection.closedIoException = new IOException(e.Message); } finally { innerConnection.ConnectionClosed?.Invoke(innerConnection.closedIoException); innerConnection.Close(); } }
public void StartPeriodic(Action action, int intervalInMilliseconds, CancellationTokenSource cancellationToken, string description) { _log.Debug($"Starting Periodic Task: {description}"); PeriodicTaskFactory.Start(action, intervalInMilliseconds, cancellationToken.Token); }
public void Start() { PeriodicTaskFactory.Start(() => { SendBulkImpressionsCount(); _running = true; }, CounterRefreshRateSeconds * 1000, _cancellationTokenSource.Token); }
private async void StartPollingTimers() { log.Trace("StartPollingTimers(): Start."); var c1 = new CancellationTokenSource(); var c2 = new CancellationTokenSource(); var c3 = new CancellationTokenSource(); var c4 = new CancellationTokenSource(); Task.Run(async() => { try { await PeriodicTaskFactory.Start( () => PlayerListCommand.RefreshPlayerList(), cancelToken: c1.Token, intervalInMilliseconds: this.Config.PollIntervalMs_PlayerListCommand, delayInMilliseconds: 1000, synchronous: true); } catch (OperationCanceledException operationCanceledException) { } catch (Exception exception) { } }); Task.Run(async() => { try { await PeriodicTaskFactory.Start( () => ServerInfoCommand.RefreshServerInfo(), cancelToken: c2.Token, intervalInMilliseconds: this.Config.PollIntervalMs_ServerInfoCommand, delayInMilliseconds: 1000, synchronous: true); } catch (OperationCanceledException operationCanceledException) { } catch (Exception exception) { } }); Task.Run(async() => { try { await PeriodicTaskFactory.Start( () => ClientChatBufferCommand.RefreshClientChatBufferCommand(), cancelToken: c3.Token, intervalInMilliseconds: this.Config.PollIntervalMs_ClientChatBufferCommand, delayInMilliseconds: 1000, synchronous: true); } catch (OperationCanceledException operationCanceledException) { } catch (Exception exception) { } }); //Task.Run(async () => //{ // try // { // await PeriodicTaskFactory.Start(() => GetAdminListCommand.RefreshAdminList(), cancelToken: c4.Token, intervalInMilliseconds: this.Config.PollIntervalMs_AdminListCommand, delayInMilliseconds: 1000, synchronous: true); // } // catch (OperationCanceledException operationCanceledException) { } //}); _pollingTimerCancelAction = new Action(() => { c1.Cancel(); c2.Cancel(); c3.Cancel(); c4.Cancel(); }); //while (true) //{ // PlayerListCommand.RefreshPlayerList(); // ServerInfoCommand.RefreshServerInfo(); // ClientChatBufferCommand.RefreshClientChatBufferCommand(); // //GetAdminListCommand.RefreshAdminList(); // await Task.Delay(StatusPullDelayMs); // if (!_connected) // break; //} log.Trace("StartPollingTimers(): End"); }
private static void BuildCachesInAssembly(Type dBContext, Assembly repAssembly, bool isRepositoryAssembly) { IEnumerable <MethodInfo> types = null; try { types = repAssembly.GetTypes() .SelectMany(type => type.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); } catch { //This exception is don't care. return; } foreach (var type in types) { var cacheInfoAtt = type.GetAttributeValue <CacheableAttribute, CacheableAttribute>(cAtt => cAtt); if (cacheInfoAtt != null) { //if (string.IsNullOrEmpty(cacheInfo.Key)) //{ // throw new ArgumentNullException("Cache Key can't be empty."); //} if ((type as MethodInfo).IsStatic) { if (!(type as MethodInfo).IsGenericMethod) { var methodInfo = type as MethodInfo; var parames = methodInfo.GetParameters(); Type funcBaseType = null; if (parames.Count() == 0) { funcBaseType = typeof(Func <>); } if (parames.Count() == 1) { funcBaseType = typeof(Func <,>); } if (parames.Count() == 2) { funcBaseType = typeof(Func <, ,>); } if (parames.Count() == 3) { funcBaseType = typeof(Func <, , ,>); } if (parames.Count() == 4) { funcBaseType = typeof(Func <, , , ,>); } if (parames.Count() == 5) { funcBaseType = typeof(Func <, , , , ,>); } List <Type> tArgs = methodInfo.GetParameters().Select(item => item.ParameterType).ToList(); tArgs.Add(methodInfo.ReturnType); var funcType = funcBaseType.MakeGenericType(tArgs.ToArray()); var funcInstanc = methodInfo.CreateDelegate(funcType); var key = funcInstanc.Method.GetHashCode().ToString(); CacheInfo currentCacheInfo = null; if (!CacheInfoDic.TryGetValue(key, out currentCacheInfo)) { // throw new ArgumentException("Duplicate cache key can't be used , please use an unique key for cache."); currentCacheInfo = CreateCacheInfo(cacheInfoAtt, methodInfo, funcInstanc, key); } try { if (typeof(IQueryable).IsAssignableFrom(methodInfo.ReturnType) && parames.Length > 0 && typeof(IQueryable).IsAssignableFrom(parames[0].ParameterType)) { if (!isRepositoryAssembly) { throw new NotSupportedException("Queryable Cache just can use in Repository Layer."); } var repository = (IRepositoryCache)Activator.CreateInstance(methodInfo.DeclaringType, Activator.CreateInstance(dBContext)); currentCacheInfo.Repository = repository; if (parames.Length == 1) { var cacheDataProviderType = typeof(QueryableCacheDataProvider <>); Type[] typeArgs = methodInfo.ReturnType.GenericTypeArguments; var cacheDataProviderGenericType = cacheDataProviderType.MakeGenericType(typeArgs); var returnCacheType = typeof(List <>).MakeGenericType(methodInfo.ReturnType.GenericTypeArguments[0]); CacheWCFTypeHelper.typeList.Add(cacheDataProviderGenericType); CacheWCFTypeHelper.typeList.Add(methodInfo.ReturnType.GenericTypeArguments[0]); CacheWCFTypeHelper.typeList.Add(returnCacheType); // if (currentCacheInfo.EnableUseCacheServer) // CacheWCFTypeHelper.typeList.Add(methodInfo.ReturnType); object queryableCacheExecution = Activator.CreateInstance(cacheDataProviderGenericType, new object[] { currentCacheInfo }); if (currentCacheInfo.FrequencyOfBuilding == 0) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); if (!cacheInfoAtt.DisableCache) { (typeof(CacheBase)).GetMethod("RefreshCache").MakeGenericMethod(returnCacheType).Invoke(null, new object[] { queryableCacheExecution, currentCacheInfo }); } stopwatch.Stop(); currentCacheInfo.FrequencyOfBuilding += 1; currentCacheInfo.BuildingTime += new TimeSpan(stopwatch.ElapsedTicks); } if (currentCacheInfo.CacheRefreshingKind == CacheRefreshingKind.Slide) { PeriodicTaskFactory p = new PeriodicTaskFactory((pt) => { if (currentCacheInfo.CountOfWaitingThreads < 3) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); ((IQueryableCacheDataProvider)queryableCacheExecution).DbContext = AppBase.DependencyInjectionFactory.CreateContextInstance(); (typeof(CacheBase)).GetMethod("RefreshCache").MakeGenericMethod(returnCacheType).Invoke(null, new object[] { queryableCacheExecution, currentCacheInfo }); stopwatch.Stop(); currentCacheInfo.FrequencyOfBuilding += 1; currentCacheInfo.BuildingTime += new TimeSpan(stopwatch.ElapsedTicks); } }, new TimeSpan(0, 0, currentCacheInfo.AutoRefreshInterval), new TimeSpan(0, 0, currentCacheInfo.AutoRefreshInterval)); p.Start(); } else { if (currentCacheInfo.CacheRefreshingKind == CacheRefreshingKind.SqlDependency) { if (currentCacheInfo.EnableSaveCacheOnHDD && currentCacheInfo.EnableToFetchOnlyChangedDataFromDB) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); if (!cacheInfoAtt.DisableCache) { ((IQueryableCacheDataProvider)queryableCacheExecution).DbContext = AppBase.DependencyInjectionFactory.CreateContextInstance(); (typeof(CacheBase)).GetMethod("RefreshCache").MakeGenericMethod(returnCacheType).Invoke(null, new object[] { queryableCacheExecution, currentCacheInfo }); } stopwatch.Stop(); currentCacheInfo.FrequencyOfBuilding += 1; currentCacheInfo.BuildingTime += new TimeSpan(stopwatch.ElapsedTicks); } var typeOfSqlNotifier = typeof(IImmediateSqlNotificationRegister <>) .MakeGenericType(currentCacheInfo.Repository.GetDomainModelType()); IImmediateSqlNotificationRegisterBase immediateSqlNotificationRegister = (IImmediateSqlNotificationRegisterBase) AppBase.DependencyInjectionManager.Resolve(typeOfSqlNotifier, new ParameterOverride("context", ((IQueryableCacheDataProvider)queryableCacheExecution).DbContext), new ParameterOverride("query", ((IQueryableCacheDataProvider)queryableCacheExecution).GetQuery())); using (var trace = new Trace.TraceDto()) { trace.TraceKey = "CacheSqlDependency"; trace.Data["CacheName"] = currentCacheInfo.Name; trace.Data["DateTime"] = DateTime.Now.ToString(); trace.Message = $"CacheSql Dependency {currentCacheInfo.Name} before configouration on startup at {DateTime.Now.ToString()} ..."; trace.Data["State"] = "config"; Core.Cmn.AppBase.TraceWriter.SubmitData(trace); } immediateSqlNotificationRegister.OnChanged += (object sender, SqlNotificationEventArgs e) => { if (currentCacheInfo.CountOfWaitingThreads < 3) { using (var trace = new Trace.TraceDto()) { trace.TraceKey = "CacheSqlDependency"; trace.Data["CacheName"] = currentCacheInfo.Name; trace.Data["DateTime"] = DateTime.Now.ToString(); trace.Message = $"CacheSql Dependency {currentCacheInfo.Name} before changing at {DateTime.Now.ToString()} ..."; trace.Data["State"] = "changing"; Core.Cmn.AppBase.TraceWriter.SubmitData(trace); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); ((IQueryableCacheDataProvider)queryableCacheExecution).DbContext = AppBase.DependencyInjectionFactory.CreateContextInstance(); immediateSqlNotificationRegister.Init(((IQueryableCacheDataProvider)queryableCacheExecution).DbContext, ((IQueryableCacheDataProvider)queryableCacheExecution).GetQuery(), currentCacheInfo); ExcecuteQueryForRefreshingSqlDependencyCache(currentCacheInfo, returnCacheType, queryableCacheExecution, 500); stopwatch.Stop(); currentCacheInfo.FrequencyOfBuilding += 1; currentCacheInfo.BuildingTime += new TimeSpan(stopwatch.ElapsedTicks); using (var trace = new Trace.TraceDto()) { trace.TraceKey = "CacheSqlDependency"; trace.Data["CacheName"] = currentCacheInfo.Name; trace.Data["DateTime"] = DateTime.Now.ToString(); trace.Message = $"CacheSql Dependency {currentCacheInfo.Name} was changed at {DateTime.Now.ToString()} ..."; trace.Data["State"] = "changing"; Core.Cmn.AppBase.TraceWriter.SubmitData(trace); } } }; using (var trace = new Trace.TraceDto()) { trace.TraceKey = "CacheSqlDependency"; trace.Data["CacheName"] = currentCacheInfo.Name; trace.Data["DateTime"] = DateTime.Now.ToString(); trace.Message = $"CacheSql Dependency {currentCacheInfo.Name} was configured on startup at {DateTime.Now.ToString()} ..."; trace.Data["State"] = "config"; Core.Cmn.AppBase.TraceWriter.SubmitData(trace); } } } } if (currentCacheInfo.EnableToFetchOnlyChangedDataFromDB && !currentCacheInfo.DisableToSyncDeletedRecord_JustIfEnableToFetchOnlyChangedDataFromDB) { CacheManagementRepository.CreateSqlTriggerForDetectingDeletedRecords(string.Format("{0}.{1}", repository.Schema, repository.TableName), repository.KeyName); } } else { if (isRepositoryAssembly) { throw new NotSupportedException("Functional Cache just can use in Service Layer."); } var Service = (IServiceCache)Activator.CreateInstance(methodInfo.DeclaringType, Activator.CreateInstance(dBContext)); Core.Cmn.AppBase.TraceWriter.SubmitData(new Trace.TraceDto { Message = $"{currentCacheInfo.Name} BuildCachesInAssembly start..." }); currentCacheInfo.Service = Service; Type cacheDataProviderType = null; if (parames.Length == 0) { cacheDataProviderType = typeof(FunctionalCacheDataProvider <>); var cacheDataProviderGenericType = AddAndGetCacheDataProviderTypeForSerialization(methodInfo, cacheDataProviderType); object functionalCacheExecution = Activator.CreateInstance(cacheDataProviderGenericType, new object[] { currentCacheInfo }); if (currentCacheInfo.FrequencyOfBuilding == 0) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); if (!cacheInfoAtt.DisableCache) { (typeof(CacheBase)).GetMethod("RefreshCache").MakeGenericMethod(methodInfo.ReturnType).Invoke(null, new object[] { functionalCacheExecution, currentCacheInfo }); } stopwatch.Stop(); currentCacheInfo.FrequencyOfBuilding += 1; currentCacheInfo.BuildingTime += new TimeSpan(stopwatch.ElapsedTicks); } if (currentCacheInfo.CacheRefreshingKind == CacheRefreshingKind.Slide) { PeriodicTaskFactory p = new PeriodicTaskFactory((pt) => { if (currentCacheInfo.CountOfWaitingThreads < 3) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); (typeof(CacheBase)).GetMethod("RefreshCache").MakeGenericMethod(methodInfo.ReturnType).Invoke(null, new object[] { functionalCacheExecution, currentCacheInfo }); stopwatch.Stop(); currentCacheInfo.FrequencyOfBuilding += 1; currentCacheInfo.BuildingTime += new TimeSpan(stopwatch.ElapsedTicks); } }, new TimeSpan(0, 0, currentCacheInfo.AutoRefreshInterval), new TimeSpan(0, 0, currentCacheInfo.AutoRefreshInterval)); p.Start(); } } else { if (parames.Length == 1) { cacheDataProviderType = typeof(FunctionalCacheDataProvider <,>); } if (parames.Length == 2) { cacheDataProviderType = typeof(FunctionalCacheDataProvider <, ,>); } if (parames.Length == 3) { cacheDataProviderType = typeof(FunctionalCacheDataProvider <, , ,>); } if (parames.Length == 4) { cacheDataProviderType = typeof(FunctionalCacheDataProvider <, , , ,>); } if (parames.Length == 5) { cacheDataProviderType = typeof(FunctionalCacheDataProvider <, , , , ,>); } AddAndGetCacheDataProviderTypeForSerialization(methodInfo, cacheDataProviderType); } Core.Cmn.AppBase.TraceWriter.SubmitData(new Trace.TraceDto { Message = $"{currentCacheInfo.Name} BuildCachesInAssembly done." }); } } catch (Exception exception) { Core.Cmn.AppBase.LogService.Handle(exception, $"{exception.Message}. Cache name: {currentCacheInfo?.Name}"); throw; } currentCacheInfo.LastBuildDateTime = DateTime.Now; } else { if (cacheInfoAtt.EnableAutomaticallyAndPeriodicallyRefreshCache) { throw new NotSupportedException($"a generic method can't call automatically for cache.If you want to use generic method set '{nameof(cacheInfoAtt.CacheRefreshingKind)}' = {nameof(CacheRefreshingKind.Slide)} in CacheableAttribute"); } } } else { throw new NotSupportedException("Cacheable Attribute can't use on Non static methods, because we can't work on nostatic method for caching."); } } } }