System.Collections.Concurrent.ConcurrentDictionary.Clear()

Here are the examples of the csharp api System.Collections.Concurrent.ConcurrentDictionary.Clear() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

936 Examples 7

19 Source : RenderDocumentCache.cs
with MIT License
from aprilyush

public static void Clear()
        {
            _douments.Clear();
        }

19 Source : IPHelper.cs
with MIT License
from aprilyush

public static void RemoveAll()
        {
            WriteList.Clear();
        }

19 Source : Cache.cs
with MIT License
from ArchaicQuest

public void ClearRoomCache()
        {
            _roomCache.Clear();
            _mapCache.Clear();
            _helpCache.Clear();
            _questCache.Clear();
            _skillCache.Clear();
            _craftingRecipesCache.Clear();

        }

19 Source : MemoryCacheMethod.cs
with MIT License
from Archomeda

public override Task ClearAsync()
        {
            this.cachedItems.Clear();
            return Task.CompletedTask;
        }

19 Source : TestsInMemoryTimeoutManager.cs
with MIT License
from ARKlab

private void _clearPendingDue()
        {
            lock (_deferredMessages)
            {
                _deferredMessages.Clear();
            }
        }

19 Source : MemoryWebHookStore.cs
with Apache License 2.0
from aspnet

public override Task DeleteAllWebHooksAsync(string user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            user = NormalizeKey(user);

            ConcurrentDictionary<string, WebHook> userHooks;
            if (_store.TryGetValue(user, out userHooks))
            {
                userHooks.Clear();
            }

            return Task.FromResult(true);
        }

19 Source : EndpointManager.cs
with Apache License 2.0
from asynkron

public void Stop()
        {
            lock (_synLock)
            {
                if (CancellationToken.IsCancellationRequested) return;

                Logger.LogDebug("[EndpointManager] Stopping");

                _system.EventStream.Unsubscribe(_endpointTerminatedEvnSub);
                _system.EventStream.Unsubscribe(_endpointConnectedEvnSub);
                _system.EventStream.Unsubscribe(_endpointErrorEvnSub);
                _system.EventStream.Unsubscribe(_deadLetterEvnSub);

                var stopEndpointTasks = 
                    _connections.Values
                    .Select(endpoint => _system.Root.StopAsync(endpoint))
                    .ToList();

                Task.WhenAll(stopEndpointTasks).GetAwaiter().GetResult();

                _cancellationTokenSource.Cancel();

                _connections.Clear();

                StopActivator();

                Logger.LogDebug("[EndpointManager] Stopped");
            }
        }

19 Source : DriverPool.cs
with Apache License 2.0
from atata-framework

public static void CloseAll()
        {
            foreach (var entries in AllEntryBags)
                Close(entries);

            ScopedEntries.Clear();
        }

19 Source : ResourceLocker.cs
with GNU General Public License v3.0
from atomex-me

public void Dispose()
        {
            foreach (var semapreplaced in _semapreplaceds.Values)
                semapreplaced.Dispose();

            _semapreplaceds.Clear();
        }

19 Source : SwapManager.cs
with GNU General Public License v3.0
from atomex-me

public void Clear()
        {
            foreach (var swapSync in SwapsSync)
            {
                var swapId = swapSync.Key;
                var semapreplaced = swapSync.Value;

                if (semapreplaced.CurrentCount == 0)
                {
                    try
                    {
                        semapreplaced.Release();
                    }
                    catch (SemapreplacedFullException)
                    {
                        Log.Warning($"Semapreplaced for swap {swapId} is already released");
                    }
                    catch (ObjectDisposedException)
                    {
                        Log.Warning($"Semapreplaced for swap {swapId} is already disposed");
                    }

                    try
                    {
                        semapreplaced.Dispose();
                    }
                    catch (Exception)
                    {
                        Log.Warning($"Semapreplaced for swap {swapId} is already disposed");
                    }
                }
            }

            SwapsSync.Clear();
        }

19 Source : RealtimeUpdate.cs
with GNU General Public License v3.0
from autodotua

public static void ClearCahces()
        {
            generatedIcons.Clear();
            generatedIcons.Clear();
        }

19 Source : ProxyService.cs
with Apache License 2.0
from AutomateThePlanet

public void ClearAllRedirectUrlPairs()
        {
            ShouldExecute();
            _redirectUrls.Clear();
        }

19 Source : KeyedLock.cs
with MIT License
from Avanade

public void Clear()
        {
            _lockDict.Clear();
        }

19 Source : RequestCache.cs
with MIT License
from Avanade

public void ClearAll()
        {
            if (_caching.IsValueCreated)
                _caching.Value.Clear();
        }

19 Source : AsyncDirectorySource.cs
with Apache License 2.0
from awslabs

protected override ValueTask BeforeDependencyAvailable(CancellationToken cancellationToken)
        {
            // if the directory is removed, the FileSystemWatcher can be re-activated 
            // by switching EnableRaisingEvents off and on again after the dir is re-created
            _watcher.EnableRaisingEvents = false;

            // directory is deleted meaning no files are there, clear all context data
            _bookmarkMap.Clear();
            _fileContextMap.Clear();
            return ValueTask.CompletedTask;
        }

19 Source : Transport.cs
with MIT License
from azist

public void ResetStats()
            {
                m_StatBytesReceived = 0;
                m_StatBytesSent = 0;
                m_StatMsgReceived = 0;
                m_StatMsgSent = 0;
                m_StatErrors = 0;

                m_Prev_StatBytesReceived = 0;
                m_Prev_StatBytesSent = 0;
                m_Prev_StatMsgReceived = 0;
                m_Prev_StatMsgSent = 0;
                m_Prev_StatErrors = 0;

                m_StatTimes.Clear();
            }

19 Source : ZoneGovernorService.cs
with MIT License
from azist

protected override void DoWaitForCompleteStop()
    {
      m_WaitEvent.Set();

      m_Thread.Join();
      m_Thread = null;

      m_WaitEvent.Close();
      m_WaitEvent = null;

      m_SubInstr.WaitForCompleteStop();
      m_SubInstrCallers.Clear();
      m_SubInstrCallerCount = 0;

      m_SubLog.WaitForCompleteStop();

      m_Locker.WaitForCompleteStop();

      base.DoWaitForCompleteStop();
    }

19 Source : AsyncCache.cs
with MIT License
from Azure

public void Clear()
        {
            ConcurrentDictionary<TKey, AsyncLazy<TValue>> newValues = new ConcurrentDictionary<TKey, AsyncLazy<TValue>>(this.keyEqualityComparer);
            ConcurrentDictionary<TKey, AsyncLazy<TValue>> oldValues = Interlocked.Exchange(ref this.values, newValues);

            // Ensure all tasks are observed.
            foreach (AsyncLazy<TValue> value in oldValues.Values)
            {
                if (value.IsValueCreated)
                {
                    Task unused = value.Value.ContinueWith(c => c.Exception, TaskContinuationOptions.OnlyOnFaulted);
                }
            }

            oldValues.Clear();
        }

19 Source : DeviceReplayTaskTest.cs
with MIT License
from Azure

private void BuildMockDeviceReplayActors(
            ConcurrentDictionary<string, Mock<IDeviceReplayActor>> mockDictionary,
            ConcurrentDictionary<string, IDeviceReplayActor> objectDictionary,
            CancellationTokenSource cancellationToken,
            int count)
        {
            mockDictionary.Clear();
            objectDictionary.Clear();

            for (int i = 0; i < count; i++)
            {
                var deviceName = $"device_{i}";
                var mockDeviceReplayActor = new Mock<IDeviceReplayActor>();

                // Have each DeviceReplayActor report that it has work to do
                mockDeviceReplayActor.Setup(x => x.HasWorkToDo()).Returns(true);
                mockDeviceReplayActor.Setup(x => x.RunAsync()).Returns(Task.CompletedTask)
                    .Callback(() => { cancellationToken.Cancel(); });

                mockDictionary.TryAdd(deviceName, mockDeviceReplayActor);
                objectDictionary.TryAdd(deviceName, mockDeviceReplayActor.Object);
            }
        }

19 Source : DeviceReplayTaskTest.cs
with MIT License
from Azure

private void BuildMockSimluationManagers(
            ConcurrentDictionary<string, Mock<ISimulationManager>> mockSimulationManagers,
            ConcurrentDictionary<string, ISimulationManager> mockSimulationManagerObjects,
            CancellationTokenSource cancellationToken,
            int count)
        {
            mockSimulationManagers.Clear();
            mockSimulationManagerObjects.Clear();

            for (int i = 0; i < count; i++)
            {
                var deviceName = $"simulation_{i}";
                var mockSimulationManager = new Mock<ISimulationManager>();

                // We only want the main loop in the target to run once, so here we'll
                // trigger a callback which will cancel the cancellation token that
                // the main loop uses.
                mockSimulationManager.Setup(x => x.NewConnectionLoop())
                    .Callback(() => cancellationToken.Cancel());

                mockSimulationManagers.TryAdd(deviceName, mockSimulationManager);
                mockSimulationManagerObjects.TryAdd(deviceName, mockSimulationManager.Object);
            }
        }

19 Source : DeviceStateTaskTest.cs
with MIT License
from Azure

private void BuildMockDeviceStateActors(
            ConcurrentDictionary<string, Mock<IDeviceStateActor>> mockDictionary,
            ConcurrentDictionary<string, IDeviceStateActor> objectDictionary,
            int count)
        {
            mockDictionary.Clear();
            objectDictionary.Clear();

            for (int i = 0; i < count; i++)
            {
                var deviceName = $"device_{i}";
                var mockDeviceStateActor = new Mock<IDeviceStateActor>();
                mockDictionary.TryAdd(deviceName, mockDeviceStateActor);
                objectDictionary.TryAdd(deviceName, mockDeviceStateActor.Object);
            }
        }

19 Source : DeviceConnectionTaskTest.cs
with MIT License
from Azure

private void BuildMockDeviceStateActors(
            ConcurrentDictionary<string, Mock<IDeviceConnectionActor>> mockDictionary,
            ConcurrentDictionary<string, IDeviceConnectionActor> objectDictionary,
            int count)
        {
            mockDictionary.Clear();
            objectDictionary.Clear();

            for (int i = 0; i < count; i++)
            {
                var deviceName = $"device_{i}";
                var mockDeviceConnectionActor = new Mock<IDeviceConnectionActor>();

                // Have each DeviceConnectionActor report that it has work to do
                mockDeviceConnectionActor.Setup(x => x.HasWorkToDo()).Returns(true);

                mockDictionary.TryAdd(deviceName, mockDeviceConnectionActor);
                objectDictionary.TryAdd(deviceName, mockDeviceConnectionActor.Object);
            }
        }

19 Source : DeviceTelemetryTaskTest.cs
with MIT License
from Azure

private void BuildMockDeviceActors(
            ConcurrentDictionary<string, Mock<IDeviceTelemetryActor>> mockDictionary,
            ConcurrentDictionary<string, IDeviceTelemetryActor> objectDictionary,
            int count,
            CancellationTokenSource cancellationToken)
        {
            mockDictionary.Clear();
            objectDictionary.Clear();

            for (int i = 0; i < count; i++)
            {
                var deviceName = $"device_{i}";
                var mockActor = new Mock<IDeviceTelemetryActor>();

                // Use a callback to cancel the token so that the main loop of
                // the target will stop after the first iteration.
                mockActor.Setup(x => x.HasWorkToDo()).Returns(true);
                mockActor.Setup(x => x.RunAsync()).Returns(Task.CompletedTask)
                    .Callback(() => { cancellationToken.Cancel(); });

                mockDictionary.TryAdd(deviceName, mockActor);
                objectDictionary.TryAdd(deviceName, mockActor.Object);
            }
        }

19 Source : UpdatePropertiesTaskTest.cs
with MIT License
from Azure

private void BuildMockActors(
            ConcurrentDictionary<string, Mock<IDevicePropertiesActor>> mockDictionary,
            ConcurrentDictionary<string, IDevicePropertiesActor> objectDictionary,
            int count)
        {
            mockDictionary.Clear();
            objectDictionary.Clear();

            for (int i = 0; i < count; i++)
            {
                var deviceName = $"device_{i}";
                var mockActor = new Mock<IDevicePropertiesActor>();

                // Have each DeviceConnectionActor report that it has work to do
                mockActor.Setup(x => x.HasWorkToDo()).Returns(true);

                mockDictionary.TryAdd(deviceName, mockActor);
                objectDictionary.TryAdd(deviceName, mockActor.Object);
            }
        }

19 Source : UpdatePropertiesTaskTest.cs
with MIT License
from Azure

private void BuildMockSimluationManagers(
            ConcurrentDictionary<string, Mock<ISimulationManager>> mockSimulationManagers,
            ConcurrentDictionary<string, ISimulationManager> mockSimulationManagerObjects,
            CancellationTokenSource cancellationToken,
            int count)
        {
            mockSimulationManagers.Clear();
            mockSimulationManagerObjects.Clear();

            for (int i = 0; i < count; i++)
            {
                var deviceName = $"simulation_{i}";
                var mockSimulationManager = new Mock<ISimulationManager>();

                // We only want the main loop in the target to run once, so here we'll
                // trigger a callback which will cancel the cancellation token that
                // the main loop uses.
                mockSimulationManager.Setup(x => x.NewPropertiesLoop())
                    .Callback(cancellationToken.Cancel);

                mockSimulationManagers.TryAdd(deviceName, mockSimulationManager);
                mockSimulationManagerObjects.TryAdd(deviceName, mockSimulationManager.Object);
            }
        }

19 Source : ExternalChildResourceCollection.cs
with MIT License
from Azure

public Task<List<FluentModelTImpl>> CommitAndGetAllAsync(CancellationToken cancellationToken)
        {
            ConcurrentBag<Exception> exceptions = new ConcurrentBag<Exception>();
            ConcurrentBag<FluentModelTImpl> comitted = new ConcurrentBag<FluentModelTImpl>();
            List<FluentModelTImpl> resources = new List<FluentModelTImpl>();
            foreach (var resource in this.collection.Values)
            {
                resources.Add(resource);
            }

            ConcurrentBag<Task> allTasks = new ConcurrentBag<Task>();
            foreach (FluentModelTImpl resource in resources.Where(r => r.PendingOperation == PendingOperation.ToBeRemoved))
            {
                FluentModelTImpl res = resource;
                Task task = res.DeleteAsync(cancellationToken)
                .ContinueWith(deleteTask =>
                    {
                        if (deleteTask.IsFaulted)
                        {
                            if (deleteTask.Exception.InnerException != null)
                            {
                                exceptions.Add(deleteTask.Exception.InnerException);
                            }
                            else
                            {
                                exceptions.Add(deleteTask.Exception);
                            }
                        }
                        else if (deleteTask.IsCanceled)
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                            exceptions.Add(new TaskCanceledException());
                        }
                        else
                        {
                            comitted.Add(res);
                            res.PendingOperation = PendingOperation.None;
                            this.collection.TryRemove(res.Name(), out FluentModelTImpl val);
                        }
                    },
                    cancellationToken,
                    TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default);
                allTasks.Add(task);
            }

            foreach (FluentModelTImpl resource in resources.Where(r => r.PendingOperation == PendingOperation.ToBeCreated))
            {
                FluentModelTImpl res = resource;
                Task task = res.CreateAsync(cancellationToken)
                .ContinueWith(createTask =>
                    {
                        if (createTask.IsFaulted)
                        {
                            this.collection.TryRemove(res.Name(), out FluentModelTImpl val);
                            if (createTask.Exception.InnerException != null)
                            {
                                exceptions.Add(createTask.Exception.InnerException);
                            }
                            else
                            {
                                exceptions.Add(createTask.Exception);
                            }
                        }
                        else if (createTask.IsCanceled)
                        {
                            this.collection.TryRemove(res.Name(), out FluentModelTImpl val);
                            cancellationToken.ThrowIfCancellationRequested();
                            exceptions.Add(new TaskCanceledException());
                        }
                        else
                        {
                            comitted.Add(res);
                            res.PendingOperation = PendingOperation.None;
                        }
                    },
                    cancellationToken,
                    TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default);
                allTasks.Add(task);
            }

            foreach (FluentModelTImpl resource in resources.Where(r => r.PendingOperation == PendingOperation.ToBeUpdated))
            {
                FluentModelTImpl res = resource;
                Task task = res.UpdateAsync(cancellationToken)
                .ContinueWith(updateTask =>
                    {
                        if (updateTask.IsFaulted)
                        {
                            if (updateTask.Exception.InnerException != null)
                            {
                                exceptions.Add(updateTask.Exception.InnerException);
                            }
                            else
                            {
                                exceptions.Add(updateTask.Exception);
                            }
                        }
                        else if (updateTask.IsCanceled)
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                            exceptions.Add(new TaskCanceledException());
                        }
                        else
                        {
                            comitted.Add(res);
                            res.PendingOperation = PendingOperation.None;
                        }
                    },
                    cancellationToken,
                    TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default);
                allTasks.Add(task);
            }

            TaskCompletionSource<List<FluentModelTImpl>> completionSource = new TaskCompletionSource<List<FluentModelTImpl>>();
            Task.WhenAll(allTasks.ToArray())
                .ContinueWith(task =>
                {
                    if (ClearAfterCommit())
                    {
                        this.collection.Clear();
                    }

                    if (exceptions.Count > 0)
                    {
                        completionSource.SetException(new AggregateException(exceptions));
                    }
                    else
                    {
                        completionSource.SetResult(comitted.ToList());
                    }
                },
                cancellationToken,
                TaskContinuationOptions.ExecuteSynchronously,
                TaskScheduler.Default);
            return completionSource.Task;
        }

19 Source : AccessKeySynchronizer.cs
with MIT License
from Azure

public void UpdateServiceEndpoints(IEnumerable<ServiceEndpoint> endpoints)
        {
            _endpoints.Clear();
            foreach (var endpoint in endpoints)
            {
                AddServiceEndpoint(endpoint);
            }
        }

19 Source : ServiceHubContextE2EFacts.cs
with MIT License
from Azure

[ConditionalTheory]
        [SkipIfConnectionStringNotPresent]
        [MemberData(nameof(TestData))]
        internal async Task TestAddUserToGroupWithTtl(ServiceTransportType serviceTransportType, string appName)
        {
            var userNames = GenerateRandomNames(ClientConnectionCount);
            var groupNames = GenerateRandomNames(GroupCount);
            var (clientEndpoint, clientAccessTokens, serviceHubContext) = await InitAsync(serviceTransportType, appName, userNames);
            try
            {
                var userGroupDict = GenerateUserGroupDict(userNames, groupNames);
                var receivedMessageDict = new ConcurrentDictionary<int, int>();
                await RunTestCore(
                    clientEndpoint,
                    clientAccessTokens,
                    () => SendToGroupCore(serviceHubContext, userGroupDict, SendAsync, (c, d) => AddUserToGroupWithTtlAsync(c, d, TimeSpan.FromSeconds(10)), Empty),
                    (userNames.Length / groupNames.Length + userNames.Length % groupNames.Length) * 2,
                    receivedMessageDict);

                await Task.Delay(TimeSpan.FromSeconds(30));
                receivedMessageDict.Clear();
                await RunTestCore(
                    clientEndpoint,
                    clientAccessTokens,
                    () => SendToGroupCore(serviceHubContext, userGroupDict, SendAsync, Empty, Empty),
                    0,
                    receivedMessageDict);
            }
            finally
            {
                await serviceHubContext.DisposeAsync();
            }

            Task SendAsync() =>
                serviceHubContext.Clients.Group(groupNames[0]).SendAsync(MethodName, Message);

            static Task Empty(IServiceHubContext context, IDictionary<string, List<string>> dict) =>
                Task.CompletedTask;
        }

19 Source : TestHubConnectionManager.cs
with MIT License
from Azure

public void ClearAll()
        {
            _connectedConnections.Clear();
            _connectedUsers.Clear();
            _connectionCountTcs.Clear();
            Interlocked.Exchange(ref _count, 0);
        }

19 Source : TestRunner.cs
with MIT License
from Azure

public async Task RunAsync(CancellationToken cancellationToken)
        {
            if (Job.ServiceSetting.Length == 0)
            {
                _logger.LogWarning("Test job {testId}: No service configuration.", Job.TestId);
                return;
            }

            while (true)
            {
                await Task.Delay(2000);
                if (Job.Dir == null)
                {
                    break;
                }

                lock (UnitLock)
                {
                    if (_dir == null || Job.Dir == _dir)
                    {
                        _dir = Job.Dir;
                        break;
                    }
                }
            }

            _timer.Start();
            _testStatusAccessor =
                await PerfStorage.GetTableAsync<TestStatusEnreplacedy>(PerfConstants.TableNames.TestStatus);
            var pairs = Job.TestId.Split("--");
            Job.TestId = Job.TestId.Replace("--", "-");
            _testStatusEnreplacedy =
                await _testStatusAccessor.GetAsync(pairs[0], pairs[1]);
            var clientAgentCount = Job.ScenarioSetting.TotalConnectionCount;
            var clientPodCount = Job.PodSetting.ClientCount;
            _logger.LogInformation("Test job {testId}: Client pods count: {count}.", Job.TestId, clientPodCount);
            var serverPodCount = Job.PodSetting.ServerCount;
            _logger.LogInformation("Test job {testId}: Server pods count: {count}.", Job.TestId, serverPodCount);
            var nodeCount = clientPodCount + serverPodCount;
            _logger.LogInformation("Test job {testId}: Node count: {count}.", Job.TestId, nodeCount);
            var asrsConnectionStringsTask = PrepairAsrsInstancesAsync(cancellationToken);
            //leave this to autoscale. When ca is enabled, manual config won't work
            // await AksProvider.EnsureNodeCountAsync(NodePoolIndex, nodeCount, cancellationToken);
            using var messageClient = await MessageClient.ConnectAsync(RedisConnectionString, Job.TestId, PodName);
            await messageClient.WithHandlers(MessageHandler.CreateCommandHandler(Roles.Coordinator,
                Commands.Coordinator.ReportClientStatus, CollectClientStatus));
            CancellationTokenSource? scheduleCts = null;
            try
            {
                var asrsConnectionStrings = await asrsConnectionStringsTask;
                await UpdateTestStatus("Creating pods, autoscaling nodes..");
                await CreatePodsAsync(asrsConnectionStrings, clientAgentCount, clientPodCount, serverPodCount,
                    messageClient, cancellationToken);
                //        await UpdateTestStatus("Starting client connections");
                var i = 0;
                var suspiciousCount = 0;
                foreach (var round in Job.ScenarioSetting.Rounds)
                {
                    i++;
                    await UpdateTestStatus($"Round {i}: Connecting");
                    var totalConnectionDeltaThisRound = GetTotalConnectionDeltaCurrentRound(i);
                    scheduleCts = new CancellationTokenSource();
                    _ = ScheduleStateUpdate(i, _roundTotalConnected, scheduleCts.Token);
                    await SetClientRange(totalConnectionDeltaThisRound, clientPodCount, messageClient,
                        cancellationToken);
                    await StartClientConnectionsAsync(messageClient, cancellationToken);
                    scheduleCts.Cancel();
                    await Task.Delay(2000);
                    _clientStatus.Clear();
                    await SetScenarioAsync(messageClient, round, cancellationToken);
                    await UpdateTestStatus($"Round {i}: Testing");
                    await StartScenarioAsync(messageClient, cancellationToken);
                    await Task.Delay(TimeSpan.FromSeconds(round.DurationInSeconds), cancellationToken);
                    await StopScenarioAsync(messageClient, cancellationToken);
                    //wait for the last message to come back
                    await Task.Delay(5000);
                    suspiciousCount= await UpdateTestReports(round, _roundTotalConnected,suspiciousCount);
                }

                // await UpdateTestStatus("Stopping client connections");
                // await StopClientConnectionsAsync(messageClient, cancellationToken);
                await UpdateTestStatus("Test Finishes");
            }
            catch (Exception e)
            {
                await UpdateTestStatus("Testing Round failed ", false, e);
            }
            finally
            {
                if (scheduleCts != null && !scheduleCts.IsCancellationRequested)
                    scheduleCts.Cancel();
                _timer.Stop();
                try
                {
                    _logger.LogInformation("Test job {testId}: Removing service instances.", Job.TestId);
                    await Task.WhenAll(
                        from ss in Job.ServiceSetting
                        where ss.AsrsConnectionString == null
                        group ss by ss.Env
                        into env
                        select SignalRProvider.GetSignalRProvider(env.Key).DeleteResourceGroupAsync(Job.TestId));
                    _logger.LogInformation("Test job {testId}: Removing hashTable in redis.", Job.TestId);
                    await messageClient.DeleteHashTableAsync();
                    _logger.LogInformation("Test job {testId}: Removing client pods.", Job.TestId);
                    await K8SProvider.DeleteClientPodsAsync(Job.TestId);
                    _logger.LogInformation("Test job {testId}: Removing server pods.", Job.TestId);
                    await K8SProvider.DeleteServerPodsAsync(Job.TestId,
                        Job.TestMethod == TestCategory.AspnetCoreSignalRServerless||Job.TestMethod == TestCategory.RawWebsocket);
                }
                catch (Exception ignore)
                {
                    await UpdateTestStatus("Clean up failed", false, ignore);
                }
                finally
                {
                    lock (UnitLock)
                    {
                        if (Job.Dir != null)
                        {
                            _unitTotal -= Job.ServiceSetting[0].Size.Value;
                            _instanceTotal--;
                            _finishedJob++;
                            if (_finishedJob == Job.Total)
                            {
                                _finishedJob = 0;
                                _instanceTotal = 0;
                                _dir = null;
                            }
                        }
                    }
                }
            }
        }

19 Source : ChunkMethodServer.cs
with MIT License
from Azure

public void Dispose() {
            _timer.Dispose();
            _requests.Clear();
        }

19 Source : DocumentDatabase.cs
with MIT License
from Azure

public void Dispose() {
            _collections.Clear();
            Client.Dispose();
        }

19 Source : LegacyJobOrchestrator.cs
with MIT License
from Azure

private void _fileSystemWatcher_Changed(object sender, FileSystemEventArgs e) {
            if (e.ChangeType == WatcherChangeTypes.Deleted) {
                _logger.Information("Published nodes file deleted, cancelling all publishing jobs");
                _lock.Wait();
                try {
                    _availableJobs.Clear();
                    _replacedignedJobs.Clear();
                    _lastKnownFileHash = string.Empty;
                }
                finally {
                    _lock.Release();
                }
            }
            else {
                RefreshJobFromFile();
            }
        }

19 Source : LegacyJobOrchestrator.cs
with MIT License
from Azure

private void RefreshJobFromFile() {
            var retryCount = 3;
            var lastWriteTime = File.GetLastWriteTime(_legacyCliModel.PublishedNodesFile);
            while (true) {
                try {
                    _lock.Wait();
                    var currentFileHash = GetChecksum(_legacyCliModel.PublishedNodesFile);
                    var availableJobs = new ConcurrentQueue<JobProcessingInstructionModel>();
                    if (currentFileHash != _lastKnownFileHash || retryCount < 3) {
                        _logger.Information("File {publishedNodesFile} has changed, last known hash {LastHash}, new hash {NewHash}, reloading...",
                            _legacyCliModel.PublishedNodesFile,
                            _lastKnownFileHash,
                            currentFileHash);
                        _lastKnownFileHash = currentFileHash;
                        using (var fileReader = new StreamReader(_legacyCliModel.PublishedNodesFile)) {
                            IEnumerable<WriterGroupJobModel> jobs = null;

                            try {
                                if (!File.Exists(_legacyCliModel.PublishedNodesSchemaFile)) {
                                    _logger.Information("Validation schema file {PublishedNodesSchemaFile} does not exist or is disabled, ignoring validation of {publishedNodesFile} file...",
                                    _legacyCliModel.PublishedNodesSchemaFile, _legacyCliModel.PublishedNodesFile);

                                    jobs = _publishedNodesJobConverter.Read(fileReader, null, _legacyCliModel);
                                }
                                else {
                                    using (var fileSchemaReader = new StreamReader(_legacyCliModel.PublishedNodesSchemaFile)) {
                                        jobs = _publishedNodesJobConverter.Read(fileReader, fileSchemaReader, _legacyCliModel);
                                    }
                                }
                            }
                            catch (IOException) {
                                throw; //preplaced it thru, to handle retries
                            }
                            catch (SerializerException ex) {
                                _logger.Information(ex, "Failed to deserialize {publishedNodesFile}, aborting reload...", _legacyCliModel.PublishedNodesFile);
                                _lastKnownFileHash = string.Empty;
                                return;
                            }

                            foreach (var job in jobs) {
                                var jobId = string.IsNullOrEmpty(job.WriterGroup.WriterGroupId)
                                        ? $"Standalone_{_idenreplacedy.DeviceId}_{Guid.NewGuid()}"
                                        : job.WriterGroup.WriterGroupId;

                                job.WriterGroup.DataSetWriters.ForEach(d => {
                                    d.DataSet.ExtensionFields ??= new Dictionary<string, string>();
                                    d.DataSet.ExtensionFields["PublisherId"] = jobId;
                                    d.DataSet.ExtensionFields["DataSetWriterId"] = d.DataSetWriterId;
                                });
                                var endpoints = string.Join(", ", job.WriterGroup.DataSetWriters.Select(w => w.DataSet.DataSetSource.Connection.Endpoint.Url));
                                _logger.Information($"Job {jobId} loaded. DataSetWriters endpoints: {endpoints}");
                                var serializedJob = _jobSerializer.SerializeJobConfiguration(job, out var jobConfigurationType);

                                availableJobs.Enqueue(
                                    new JobProcessingInstructionModel {
                                        Job = new JobInfoModel {
                                            Demands = new List<DemandModel>(),
                                            Id = jobId,
                                            JobConfiguration = serializedJob,
                                            JobConfigurationType = jobConfigurationType,
                                            LifetimeData = new JobLifetimeDataModel(),
                                            Name = jobId,
                                            RedundancyConfig = new RedundancyConfigModel { DesiredActiveAgents = 1, DesiredPreplacediveAgents = 0 }
                                        },
                                        ProcessMode = ProcessMode.Active
                                    });
                            }
                        }
                        if (_agentConfig.MaxWorkers < availableJobs.Count && availableJobs.Count > 1) {
                            _agentConfig.MaxWorkers = availableJobs.Count;

                            ThreadPool.GetMinThreads(out var workerThreads, out var asyncThreads);
                            if (_agentConfig.MaxWorkers > workerThreads ||
                                _agentConfig.MaxWorkers > asyncThreads) {
                                var result = ThreadPool.SetMinThreads(_agentConfig.MaxWorkers.Value, _agentConfig.MaxWorkers.Value);
                                _logger.Information("Thread pool changed to: worker {worker}, async {async} threads {succeeded}",
                                    _agentConfig.MaxWorkers.Value, _agentConfig.MaxWorkers.Value, result ? "succeeded" : "failed");
                            }
                        }
                        _availableJobs = availableJobs;
                        _replacedignedJobs.Clear();
                    } else {
                        //avoid double events from FileSystemWatcher
                        if (lastWriteTime - _lastRead > TimeSpan.FromMilliseconds(10)) {
                            _logger.Information("File {publishedNodesFile} has changed and content-hash is equal to last one, nothing to do", _legacyCliModel.PublishedNodesFile);
                        }
                    }
                    _lastRead = lastWriteTime;
                    break;
                }
                catch (IOException ex) {
                    retryCount--;

                    if (retryCount > 0) {
                        _logger.Error(ex, "Error while loading job from file. Retrying...");
                        Task.Delay(5000).GetAwaiter().GetResult();
                    }
                    else {
                        _logger.Error(ex, "Error while loading job from file. Retry expired, giving up.");
                        break;
                    }
                }
                catch (Exception e) {
                    _logger.Error(e, "Error while reloading {PublishedNodesFile}", _legacyCliModel.PublishedNodesFile);
                    _availableJobs.Clear();
                    _replacedignedJobs.Clear();
                }
                finally {
                    _lock.Release();
                }
            }
        }

19 Source : DataUploadServices.cs
with MIT License
from Azure

public void Dispose() {
            if (_tasks.Count != 0) {
                Task.WaitAll(_tasks.Values.Select(t => t.CancelAsync()).ToArray());
                _tasks.Clear();
            }
        }

19 Source : RequestState.cs
with MIT License
from Azure

public void Dispose() {
            var operations = _requests.Values.ToList();
            _requests.Clear();
            foreach (var operation in operations) {
                operation.SetStatusCode(StatusCodes.BadSessionClosed);
            }
        }

19 Source : LoRaConsoleLogger.cs
with MIT License
from Azure

protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.loggers.Clear();
                this.onChangeToken.Dispose();
            }
        }

19 Source : ColorConsoleLoggerProvider.cs
with MIT License
from Azure-Samples

public void Dispose()
        {
            _loggers.Clear();
        }

19 Source : ColorConsoleLogger.cs
with MIT License
from Azure-Samples

public void Dispose()
        {
            _loggers.Clear();
            _onChangeToken.Dispose();
        }

19 Source : MockReliableDictionary.cs
with MIT License
from Azure-Samples

public Task ClearAsync()
        {
            this.dictionary.Clear();

            return Task.FromResult(true);
        }

19 Source : MockReliableStateManager.cs
with MIT License
from Azure-Samples

public Task ClearAsync(ITransaction tx)
        {
            this.store.Clear();
            return Task.FromResult(true);
        }

19 Source : MockReliableStateManager.cs
with MIT License
from Azure-Samples

public Task ClearAsync()
        {
            this.store.Clear();
            return Task.FromResult(true);
        }

19 Source : MockReliableDictionary.cs
with MIT License
from Azure-Samples

public Task ClearAsync(TimeSpan timeout, CancellationToken cancellationToken)
        {
            this.dictionary.Clear();

            return Task.FromResult(true);
        }

19 Source : X11Client.cs
with MIT License
from azyobuzin

private async void ReceiveWorker()
        {
            const int eventSize = 32;
            var eventBuffer = new byte[eventSize];
            var replyBuffer = new byte[256];

            try
            {
                while (true)
                {
                    await this.ReadExactAsync(eventBuffer, eventSize).ConfigureAwait(false);

                    var header = Unsafe.ReadUnaligned<EventOrReplyHeader>(ref eventBuffer[0]);
                    Debug.WriteLine("Received " + header.EventType);

                    if (header.EventType == 0) // Error
                    {
                        await callReplyAction(header.SequenceNumber, null, null, new X11Exception(header.ErrorCode.ToString()))
                            .ConfigureAwait(false);
                    }
                    else if (header.EventType == 1) // Reply
                    {
                        var replyLength = header.ReplyLength * 4;

                        if (replyLength > 0)
                        {
                            EnsureBufferSize(ref replyBuffer, replyLength);
                            await this.ReadExactAsync(replyBuffer, replyLength).ConfigureAwait(false);
                        }

                        await callReplyAction(header.SequenceNumber, eventBuffer, replyBuffer, null).ConfigureAwait(false);
                    }
                    else
                    {
                        // TODO: イベント処理
                    }
                }
            }
            catch (Exception ex)
            {
                if (!this._disposed)
                {
                    foreach (var kvp in this._replyActions)
                        kvp.Value?.Invoke(null, null, ex);

                    this._replyActions.Clear();

                    // TODO: イベント購読者に例外を流す

                    this.Dispose();
                }
            }

            Task callReplyAction(ushort sequenceNumber, byte[] replyHeader, byte[] replyContent, Exception exception)
            {
                this._replyActions.TryRemove(sequenceNumber, out var replyAction);
                if (replyAction == null) throw new InvalidOperationException("The reply action was not set.");
                return replyAction(replyHeader, replyContent, exception);
            }
        }

19 Source : DalamudServer.cs
with GNU General Public License v3.0
from BardMusicPlayer

public void Dispose()
        {
            try
            {
                Stop();
                _pipe.MessageReceived -= OnMessage;
                _pipe.ClientConnected -= OnDisconnected;
                _pipe.ClientDisconnected -= OnConnected;
                _pipe.DisposeAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Dalamud error: {ex.Message}");
            }
            _clients.Clear();
        }

19 Source : Node.cs
with GNU General Public License v3.0
from BardMusicPlayer

void ClearNode()
        {
            _id = 0x0;
            _primaryPort = 0;
            _secondaryPort = 0;
            _tertiaryPort = 0;
            _versionMajor = 0;
            _versionMinor = 0;
            _versionRev = 0;
            _isOnline = false;
            _configFilePath = string.Empty;
            _networks.Clear();
            _peers.Clear();
        }

19 Source : BmpSeer.cs
with GNU General Public License v3.0
from BardMusicPlayer

public void Stop()
        {
            if (!Started) return;
            StopProcessWatcher();
            StopEventsHandler();
            foreach (var game in _games.Values) game?.Dispose();
            _games.Clear();
            Started = false;
        }

19 Source : ChromeSession.cs
with MIT License
from BaristaLabs

private void Dispose(bool disposing)
        {
            if (!m_isDisposed)
            {
                if (disposing)
                {
                    //Clear all subscribed events.
                    m_eventHandlers.Clear();
                    m_eventTypeMap.Clear();

                    if (m_sessionSocket != null)
                    {
                        m_sessionSocket.Opened -= Ws_Opened;
                        m_sessionSocket.Error -= Ws_Error;
                        m_sessionSocket.MessageReceived -= Ws_MessageReceived;
                        m_sessionSocket.Dispose();
                        m_sessionSocket = null;
                    }

                    if (m_messageQueue != null)
                    {
                        m_messageQueue.Complete();
                        m_messageQueue = null;
                    }

                    if (m_openEvent != null)
                    {
                        m_openEvent.Dispose();
                        m_openEvent = null;
                    }

                    if (m_responseReceived != null)
                    {
                        m_responseReceived.Dispose();
                        m_responseReceived = null;
                    }
                }

                m_isDisposed = true;
            }
        }

19 Source : SkraprDevTools.cs
with MIT License
from BaristaLabs

private void ProcessDoreplacedentUpdatedEvent(Dom.DoreplacedentUpdatedEvent e)
        {
            m_nodeDictionary.Clear();
            m_responseDictionary.Clear();
        }

19 Source : SkraprDevTools.cs
with MIT License
from BaristaLabs

private void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                if (disposing)
                {
                    m_session.Dispose();

                    m_frameStoppedLoading.Dispose();
                    m_childNodeEvent.Dispose();
                    m_nodeDictionary.Clear();
                }

                m_disposed = true;
            }
        }

See More Examples