System.Threading.ManualResetEventSlim.Set()

Here are the examples of the csharp api System.Threading.ManualResetEventSlim.Set() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

584 Examples 7

19 Source : ObjectPool.cs
with MIT License
from 2881099

public void Return(Object<T> obj, bool isReset = false)
        {

            if (obj == null) return;

            if (obj._isReturned) return;

            if (running == false)
            {

                Policy.OnDestroy(obj.Value);
                try { (obj.Value as IDisposable)?.Dispose(); } catch { }

                return;
            }

            if (isReset) obj.ResetValue();

            bool isReturn = false;

            while (isReturn == false && _getQueue.TryDequeue(out var isAsync))
            {

                if (isAsync == false)
                {

                    if (_getSyncQueue.TryDequeue(out var queueItem) && queueItem != null)
                    {

                        lock (queueItem.Lock)
                            if (queueItem.IsTimeout == false)
                                queueItem.ReturnValue = obj;

                        if (queueItem.ReturnValue != null)
                        {

                            obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId;
                            obj.LastReturnTime = DateTime.Now;

                            try
                            {
                                queueItem.Wait.Set();
                                isReturn = true;
                            }
                            catch
                            {
                            }
                        }

                        try { queueItem.Dispose(); } catch { }
                    }

                }
                else
                {

                    if (_getAsyncQueue.TryDequeue(out var tcs) && tcs != null && tcs.Task.IsCanceled == false)
                    {

                        obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId;
                        obj.LastReturnTime = DateTime.Now;

                        try { isReturn = tcs.TrySetResult(obj); } catch { }
                    }
                }
            }

            //无排队,直接归还
            if (isReturn == false)
            {
                try
                {
                    Policy.OnReturn(obj);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId;
                    obj.LastReturnTime = DateTime.Now;
                    obj._isReturned = true;

                    _freeObjects.Push(obj);
                }
            }
        }

19 Source : ObjectPool.cs
with MIT License
from 2881099

public void Dispose()
        {

            running = false;

            while (_freeObjects.TryPop(out var fo)) ;

            while (_getSyncQueue.TryDequeue(out var sync))
            {
                try { sync.Wait.Set(); } catch { }
            }

            while (_getAsyncQueue.TryDequeue(out var async))
                async.TrySetCanceled();

            while (_getQueue.TryDequeue(out var qs)) ;

            for (var a = 0; a < _allObjects.Count; a++)
            {
                Policy.OnDestroy(_allObjects[a].Value);
                try { (_allObjects[a].Value as IDisposable)?.Dispose(); } catch { }
            }

            _allObjects.Clear();
        }

19 Source : TestAppender.cs
with MIT License
from Abc-Arbitrage

public void WriteEvent(ILogEventHeader logEventHeader, byte[] messageBytes, int messageLength)
        {
            if (_captureLoggedMessages)
                LoggedMessages.Add(Encoding.ASCII.GetString(messageBytes, 0, messageLength));

            if (++_messageCount == _messageCountTarget)
                _signal.Set();

            WaitOnWriteEvent?.Wait();
        }

19 Source : Log4NetTestAppender.cs
with MIT License
from Abc-Arbitrage

protected override void Append(LoggingEvent loggingEvent)
        {
            var formatted = loggingEvent.RenderedMessage;

            if (_captureLoggedMessages)
                LoggedMessages.Add(loggingEvent.ToString());

            if (++_messageCount == _messageCountTarget)
                _signal.Set();
        }

19 Source : NLogTestTarget.cs
with MIT License
from Abc-Arbitrage

protected override void Write(LogEventInfo logEvent)
        {
            string logMessage = this.Layout.Render(logEvent);

            if (_captureLoggedMessages)
                LoggedMessages.Add(logMessage);

            if (++_messageCount == _messageCountTarget)
                _signal.Set();
        }

19 Source : TDLibHost.cs
with MIT License
from ADeltaX

public async Task CreateInstance()
        {
            TDLibHostBot = this;

            _client = new TdClient();
            TdLog.SetVerbosityLevel(0);

            _client.UpdateReceived += async (sender, update) =>
            {
                switch (update)
                {
                    case Update.UpdateOption option:
                        await _client.ExecuteAsync(new SetOption
                        {
                            DataType = option.DataType,
                            Extra = option.Extra,
                            Name = option.Name,
                            Value = option.Value
                        });
                        break;
                    case Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitTdlibParameters):
                        await _client.ExecuteAsync(new SetTdlibParameters
                        {
                            Parameters = new TdlibParameters
                            {
                                ApiId = SecretKeys.API_ID,
                                ApiHash = SecretKeys.API_HASH,
                                ApplicationVersion = "1.0.0",
                                DeviceModel = "PC",
                                SystemLanguageCode = "en",
                                SystemVersion = "Win 10.0",
                                DatabaseDirectory = Path.Combine(Directory.GetCurrentDirectory(), "tdlib"),
                                EnableStorageOptimizer = true,
                                FilesDirectory = Path.Combine(Directory.GetCurrentDirectory(), "tdlib")
                            }
                        });
                        break;
                    case Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitEncryptionKey):
                        await _client.ExecuteAsync(new CheckDatabaseEncryptionKey());
                        break;
                    case Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitCode):
                    case Update.UpdateAuthorizationState updateAuthorizationState2 when updateAuthorizationState2.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitPhoneNumber):
                        _authNeeded = true;
                        ResetEvent.Set();
                        break;
                    case Update.UpdateUser updateUser:
                        break;
                    case Update.UpdateConnectionState updateConnectionState when updateConnectionState.State.GetType() == typeof(ConnectionState.ConnectionStateReady):
                        ResetEvent.Set();
                        ReadyEvent.Set();
                        break;

                    case Update.UpdateMessageSendFailed uwu:
                    case Update.UpdateMessageSendSucceeded uwu2:
                        //what happens ?
                        //BIG *RIP*
                        UploadedEvent.Set();
                        break;

                    default:
                        break;
                }
            };

#if !PRODUCTION
            await Cont(TelegramBotSettings.DEV_CHANNEL);
#else
            await Cont(TelegramBotSettings.PROD_CHANNEL);
#endif
        }

19 Source : ConnectionPool.cs
with Mozilla Public License 2.0
from agebullhu

public void ReleaseConnection(RedisConnection2 conn, bool isReset = false)
        {
            if (isReset)
            {
                try
                {
                    conn.Client.Quit();
                }
                catch
                {
                }

                var ips = Dns.GetHostAddresses(_ip);
                if (ips.Length == 0) throw new Exception($"无法解析“{_ip}”");
                try
                {
                    conn.Client.Dispose();
                }
                catch
                {
                }

                conn.Client = new RedisClient(new IPEndPoint(ips[0], _port), _ssl, 1000, _writebuffer);
                conn.Client.Connected += Connected;
            }

            lock (_lock)
            {
                FreeConnections.Enqueue(conn);
            }

            var isAsync = false;
            if (GetConnectionAsyncQueue.Count > 0)
            {
                lock (_lock_GetConnectionQueue)
                {
                    if (GetConnectionAsyncQueue.Count > 0)
                    {
                        var tcs = GetConnectionAsyncQueue.Dequeue();
                        isAsync = tcs != null;
                        if (isAsync)
                            tcs.SetResult(GetConnectionAsync().Result);
                    }
                }
            }

            if (isAsync || GetConnectionQueue.Count <= 0)
                return;
            ManualResetEventSlim wait = null;
            lock (_lock_GetConnectionQueue)
            {
                if (GetConnectionQueue.Count > 0)
                    wait = GetConnectionQueue.Dequeue();
            }

            wait?.Set();
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void GetCurrentKeyRing_NoExistingKeyRing_HoldsAllThreadsUntilKeyRingCreated()
        {
            // Arrange
            var now = StringToDateTime("2015-03-01 00:00:00Z");
            var expectedKeyRing = new Mock<IKeyRing>().Object;
            var mockCacheableKeyRingProvider = new Mock<ICacheableKeyRingProvider>();
            var keyRingProvider = CreateKeyRingProvider(mockCacheableKeyRingProvider.Object);

            // This test spawns a background thread which calls GetCurrentKeyRing then waits
            // for the foreground thread to call GetCurrentKeyRing. When the foreground thread
            // blocks (inside the lock), the background thread will return the cached keyring
            // object, and the foreground thread should consume that same object instance.

            TimeSpan testTimeout = TimeSpan.FromSeconds(10);

            Thread foregroundThread = Thread.CurrentThread;
            ManualResetEventSlim mreBackgroundThreadHasCalledGetCurrentKeyRing = new ManualResetEventSlim();
            ManualResetEventSlim mreForegroundThreadIsCallingGetCurrentKeyRing = new ManualResetEventSlim();
            var backgroundGetKeyRingTask = Task.Run(() =>
            {
                mockCacheableKeyRingProvider
                    .Setup(o => o.GetCacheableKeyRing(now))
                    .Returns(() =>
                    {
                        mreBackgroundThreadHasCalledGetCurrentKeyRing.Set();
                        replacedert.True(mreForegroundThreadIsCallingGetCurrentKeyRing.Wait(testTimeout), "Test timed out.");
                        SpinWait.SpinUntil(() => (foregroundThread.ThreadState & ThreadState.WaitSleepJoin) != 0, testTimeout);
                        return new CacheableKeyRing(
                            expirationToken: CancellationToken.None,
                            expirationTime: StringToDateTime("2015-03-02 00:00:00Z"),
                            keyRing: expectedKeyRing);
                    });

                return keyRingProvider.GetCurrentKeyRingCore(now);
            });

            replacedert.True(mreBackgroundThreadHasCalledGetCurrentKeyRing.Wait(testTimeout), "Test timed out.");
            mreForegroundThreadIsCallingGetCurrentKeyRing.Set();
            var foregroundRetVal = keyRingProvider.GetCurrentKeyRingCore(now);
            backgroundGetKeyRingTask.Wait(testTimeout);
            var backgroundRetVal = backgroundGetKeyRingTask.GetAwaiter().GetResult();

            // replacedert - underlying provider only should have been called once
            replacedert.Same(expectedKeyRing, foregroundRetVal);
            replacedert.Same(expectedKeyRing, backgroundRetVal);
            mockCacheableKeyRingProvider.Verify(o => o.GetCacheableKeyRing(It.IsAny<DateTimeOffset>()), Times.Once);
        }

19 Source : DiscordClient.WebSocket.cs
with MIT License
from Aiko-IT-Systems

internal async Task InternalConnectAsync()
        {
            SocketLock socketLock = null;
            try
            {
                if (this.GatewayInfo == null)
                    await this.InternalUpdateGatewayAsync().ConfigureAwait(false);
                await this.InitializeAsync().ConfigureAwait(false);

                socketLock = this.GetSocketLock();
                await socketLock.LockAsync().ConfigureAwait(false);
            }
            catch
            {
                socketLock?.UnlockAfter(TimeSpan.Zero);
                throw;
            }

            if (!this.Presences.ContainsKey(this.CurrentUser.Id))
            {
                this._presences[this.CurrentUser.Id] = new DiscordPresence
                {
                    Discord = this,
                    RawActivity = new TransportActivity(),
                    Activity = new DiscordActivity(),
                    Status = UserStatus.Online,
                    InternalUser = new TransportUser
                    {
                        Id = this.CurrentUser.Id,
                        Username = this.CurrentUser.Username,
                        Discriminator = this.CurrentUser.Discriminator,
                        AvatarHash = this.CurrentUser.AvatarHash
                    }
                };
            }
            else
            {
                var pr = this._presences[this.CurrentUser.Id];
                pr.RawActivity = new TransportActivity();
                pr.Activity = new DiscordActivity();
                pr.Status = UserStatus.Online;
            }

            Volatile.Write(ref this._skippedHeartbeats, 0);

            this._webSocketClient = this.Configuration.WebSocketClientFactory(this.Configuration.Proxy, this.ServiceProvider);
            this._payloadDecompressor = this.Configuration.GatewayCompressionLevel != GatewayCompressionLevel.None
                ? new PayloadDecompressor(this.Configuration.GatewayCompressionLevel)
                : null;

            this._cancelTokenSource = new CancellationTokenSource();
            this._cancelToken = this._cancelTokenSource.Token;

            this._webSocketClient.Connected += SocketOnConnect;
            this._webSocketClient.Disconnected += SocketOnDisconnect;
            this._webSocketClient.MessageReceived += SocketOnMessage;
            this._webSocketClient.ExceptionThrown += SocketOnException;

            var gwuri = new QueryUriBuilder(this.GatewayUri)
                .AddParameter("v", this.Configuration.ApiVersion)
                .AddParameter("encoding", "json");

            if (this.Configuration.GatewayCompressionLevel == GatewayCompressionLevel.Stream)
                gwuri.AddParameter("compress", "zlib-stream");

            await this._webSocketClient.ConnectAsync(gwuri.Build()).ConfigureAwait(false);

            Task SocketOnConnect(IWebSocketClient sender, SocketEventArgs e)
                => this._socketOpened.InvokeAsync(this, e);

            async Task SocketOnMessage(IWebSocketClient sender, SocketMessageEventArgs e)
            {
                string msg = null;
                if (e is SocketTextMessageEventArgs etext)
                {
                    msg = etext.Message;
                }
                else if (e is SocketBinaryMessageEventArgs ebin) // :DDDD
                {
                    using var ms = new MemoryStream();
                    if (!this._payloadDecompressor.TryDecompress(new ArraySegment<byte>(ebin.Message), ms))
                    {
                        this.Logger.LogError(LoggerEvents.WebSocketReceiveFailure, "Payload decompression failed");
                        return;
                    }

                    ms.Position = 0;
                    using var sr = new StreamReader(ms, Utilities.UTF8);
                    msg = await sr.ReadToEndAsync().ConfigureAwait(false);
                }

                try
                {
                    this.Logger.LogTrace(LoggerEvents.GatewayWsRx, msg);
                    await this.HandleSocketMessageAsync(msg).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    this.Logger.LogError(LoggerEvents.WebSocketReceiveFailure, ex, "Socket handler suppressed an exception");
                }
            }

            Task SocketOnException(IWebSocketClient sender, SocketErrorEventArgs e)
                => this._socketErrored.InvokeAsync(this, e);

            async Task SocketOnDisconnect(IWebSocketClient sender, SocketCloseEventArgs e)
            {
                // release session and connection
                this.ConnectionLock.Set();
                this.SessionLock.Set();

                if (!this._disposed)
                    this._cancelTokenSource.Cancel();

                this.Logger.LogDebug(LoggerEvents.ConnectionClose, "Connection closed ({0}, '{1}')", e.CloseCode, e.CloseMessage);
                await this._socketClosed.InvokeAsync(this, e).ConfigureAwait(false);



                if (this.Configuration.AutoReconnect && (e.CloseCode < 4001 || e.CloseCode >= 5000))
                {
                    this.Logger.LogCritical(LoggerEvents.ConnectionClose, "Connection terminated ({0}, '{1}'), reconnecting", e.CloseCode, e.CloseMessage);

                    if (this._status == null)
                        await this.ConnectAsync().ConfigureAwait(false);
                    else
                        if (this._status.IdleSince.HasValue)
                        await this.ConnectAsync(this._status._activity, this._status.Status, Utilities.GetDateTimeOffsetFromMilliseconds(this._status.IdleSince.Value)).ConfigureAwait(false);
                    else
                        await this.ConnectAsync(this._status._activity, this._status.Status).ConfigureAwait(false);
                }
                else
                {
                    this.Logger.LogCritical(LoggerEvents.ConnectionClose, "Connection terminated ({0}, '{1}')", e.CloseCode, e.CloseMessage);
                }
            }
        }

19 Source : ConcatDeadlockTest.cs
with Apache License 2.0
from akarnokd

[Test]
        public void TestMethod1()
        {
            CountdownEvent printed = null;
            var nextInnerQuery = new Subject<Unit>();
            IEnumerable<object> e = null;
            Action<string> afterSelectManyButBeforeConcat = _ => { };

            (from _ in nextInnerQuery
             select (from __ in Observable.Return(Unit.Default)
                     from completeSynchronously in e
                     from x in SyncOrAsync(completeSynchronously as string, completeSynchronously as IObservable<string>)
                     select x)
                     .Do(x => afterSelectManyButBeforeConcat(x)))
            .ConcatMany()
            .Subscribe(x =>
            {
                Console.WriteLine(x);
                printed.Signal();
            });


            Console.WriteLine("No deadlock...");

            printed = new CountdownEvent(2);
            e = new[] { "Sync 1", "Sync 2" };
            nextInnerQuery.OnNext(Unit.Default);

            printed.Wait();


            Console.WriteLine("Also no deadlock...");

            printed = new CountdownEvent(2);
            var first = new Subject<string>();
            var second = new Subject<string>();
            e = new[] { first, second };
            nextInnerQuery.OnNext(Unit.Default);
            first.OnNext("Async 1");
            second.OnNext("Async 2");

            printed.Wait();


            Console.WriteLine("DEADLOCK");

            printed = new CountdownEvent(2);
            var waitForAsyncOnThreadB = new ManualResetEventSlim();
            var asyncValue = new Subject<string>();

            // Thread B
            afterSelectManyButBeforeConcat = _ => waitForAsyncOnThreadB.Set();

            e = AsyncThenSync(
              asyncValue,
              "Sync 2",
              () =>
              {
            // Thread A
            asyncValue.OnNext("Async 1");
            // Thread B: SelectMany.OnNext acquires a lock
            //           (waitForAsyncOnThreadB is set)
            //           Concat blocks awaiting the lock acquired initially by Thread A.
            //           Order of locks: SelectMany -> Concat (DEADLOCK)

            // Thread A
            waitForAsyncOnThreadB.Wait();
              });

            // Thread A
            nextInnerQuery.OnNext(Unit.Default);   // Thread A: Concat (technically, Merge(1)) acquires and holds a lock while iterating 'e'

            // This line is never reached, and nothing is ever printed.
            printed.Wait();
        }

19 Source : OnScreenKeyboardWatcher.cs
with MIT License
from AlexeiScherbakov

private void Terminate()
		{
			_endEvent.Set();
			if (!_watcherThread.Join(500))
			{
				_watcherThread.Abort();
			}
		}

19 Source : JupyterClient.cs
with MIT License
from andreaschiavinato

private void MonitorChannels()
        {
            var poll = ZPollItem.CreateReceiver();
            ZMessage incoming;
            ZError error;
            while (!_monitorChannnelsCts.IsCancellationRequested)
            {
                if (_monitorChannnelsCts.IsCancellationRequested)
                    break;

                if (StdInSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(100)))
                {
                    ProcessMessage(incoming, error);
                }

                if (_monitorChannnelsCts.IsCancellationRequested)
                    break;

                if (IoPubSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(100)))
                {
                    ProcessMessage(incoming, error);
                }

                if (_monitorChannnelsCts.IsCancellationRequested)
                    break;

                if (ShellSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(100)))
                {
                    ProcessMessage(incoming, error);
                }

                if (_monitorChannnelsCts.IsCancellationRequested)
                    break;

                if (ControlSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(100)))
                {
                    ProcessMessage(incoming, error);
                }
            }
            ContinueShutdown.Set();
        }

19 Source : FolderWatcherService.cs
with MIT License
from AntonyCorbett

private void HandleContentModified(object sender, FileSystemEventArgs e)
        {
            switch (e.ChangeType)
            {
                case WatcherChangeTypes.Created:
                case WatcherChangeTypes.Changed:
                case WatcherChangeTypes.Deleted:
                    if (!_mediaProviderService.IsFileExtensionSupported(Path.GetExtension(e.FullPath)))
                    {
                        // not a relevant file.
                        return;
                    }

                    break;
            }

            if (!IsWatchingFilesFolder(e.FullPath))
            {
                return;
            }
            
            Interlocked.Increment(ref _changeVersion);
            _signalFolderChange.Set();
        }

19 Source : FolderWatcherService.cs
with MIT License
from AntonyCorbett

private void HandleContentRenamed(object sender, RenamedEventArgs e)
        {
            if (!_mediaProviderService.IsFileExtensionSupported(Path.GetExtension(e.OldFullPath)) &&
                !_mediaProviderService.IsFileExtensionSupported(Path.GetExtension(e.FullPath)))
            {
                // not a relevant file.
                return;
            }

            if (!IsWatchingFilesFolder(e.OldFullPath) && !IsWatchingFilesFolder(e.FullPath))
            {
                return;
            }

            Interlocked.Increment(ref _changeVersion);
            _signalFolderChange.Set();
        }

19 Source : ModbusServer.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

public void Update()
        {
            if (this.IsAsynchronous || !this.IsReady)
                return;

            _manualResetEvent.Set();
        }

19 Source : ModbusServer.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

public virtual void StopProcessing()
        {
            this.CTS?.Cancel();
            _manualResetEvent?.Set();

            try
            {
                _task_process_requests?.Wait();
            }
            catch (Exception ex) when (ex.InnerException.GetType() == typeof(TaskCanceledException))
            {
                //
            }
        }

19 Source : AsyncQueueDispatcher.cs
with MIT License
from AspectCore

public bool Dispatch(IPayload payload)
        {
            if (_status && !_cancellationTokenSource.IsCancellationRequested && _queue.Count < _maxCapacity)
            {
                _queue.Enqueue(payload);
                if (!_eventSlim.IsSet)
                {
                    _eventSlim.Set();
                }
                return true;
            }
            return false;
        }

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

internal override void StartCleanupTimer()
            {
                if (EnableCleanupTimer)
                {
                    CleanupTimerStarted.Set();
                }
            }

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

private void OnStartingBackgroundWork()
        {
            if (BlockBackgroundWorkStart != null)
            {
                BlockBackgroundWorkStart.Wait();
                BlockBackgroundWorkStart.Reset();
            }

            if (NotifyBackgroundWorkStarting != null)
            {
                NotifyBackgroundWorkStarting.Set();
            }
        }

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

private void OnStartingRefreshWork()
        {
            if (BlockRefreshWorkStarting != null)
            {
                BlockRefreshWorkStarting.Wait();
                BlockRefreshWorkStarting.Reset();
            }

            if (NotifyRefreshWorkStarting != null)
            {
                NotifyRefreshWorkStarting.Set();
            }
        }

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

private void OnRefreshWorkCompleting()
        {
            if (NotifyRefreshWorkCompleting != null)
            {
                NotifyRefreshWorkCompleting.Set();
            }
        }

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

private void OnCompletedBackgroundWork()
        {
            if (NotifyBackgroundWorkCompleted != null)
            {
                NotifyBackgroundWorkCompleted.Set();
            }
        }

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

private void OnBackgroundCapturedWorkload()
        {
            if (NotifyBackgroundCapturedWorkload != null)
            {
                NotifyBackgroundCapturedWorkload.Set();
            }
        }

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

[Fact]
        public async Task ProjectLoaded_TriggersUpdate()
        {
            // Arrange
            await RunOnForegroundAsync(() => ProjectManager.ProjectAdded(Project1));
            var mre = new ManualResetEventSlim(initialState: false);
            var workspaceStateGenerator = new Mock<OmniSharpProjectWorkspaceStateGenerator>();
            workspaceStateGenerator.Setup(generator => generator.Update(It.IsAny<Project>(), It.IsAny<OmniSharpProjectSnapshot>()))
                .Callback<Project, OmniSharpProjectSnapshot>((_, __) => mre.Set());
            var refreshTrigger = CreateRefreshTrigger(workspaceStateGenerator.Object);
            var args = new ProjectLoadedEventArgs(
                null,
                Project1Instance,
                EmptyDiagnostics,
                isReload: false,
                projectIdIsDefinedInSolution: false,
                sourceFiles: Enumerable.Empty<string>().ToImmutableArray());

            // Act
            refreshTrigger.ProjectLoaded(args);

            // replacedert
            var result = mre.Wait(WaitDelay);
            replacedert.True(result);
        }

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

[Fact]
        public async Task ProjectLoaded_BatchesUpdates()
        {
            // Arrange
            await RunOnForegroundAsync(() => ProjectManager.ProjectAdded(Project1));
            var mre = new ManualResetEventSlim(initialState: false);
            var workspaceStateGenerator = new Mock<OmniSharpProjectWorkspaceStateGenerator>();
            workspaceStateGenerator.Setup(generator => generator.Update(It.IsAny<Project>(), It.IsAny<OmniSharpProjectSnapshot>()))
                .Callback<Project, OmniSharpProjectSnapshot>((_, __) =>
                {
                    if (mre.IsSet)
                    {
                        throw new XunitException("Should not have been called twice.");
                    }

                    mre.Set();
                });
            var refreshTrigger = CreateRefreshTrigger(workspaceStateGenerator.Object, enqueueDelay: 10);
            var args = new ProjectLoadedEventArgs(
                null,
                Project1Instance,
                EmptyDiagnostics,
                isReload: false,
                projectIdIsDefinedInSolution: false,
                sourceFiles: Enumerable.Empty<string>().ToImmutableArray());

            // Act
            refreshTrigger.ProjectLoaded(args);
            refreshTrigger.ProjectLoaded(args);
            refreshTrigger.ProjectLoaded(args);
            refreshTrigger.ProjectLoaded(args);

            // replacedert
            var result = mre.Wait(WaitDelay);
            replacedert.True(result);
        }

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

[Fact]
        public async Task RazorDoreplacedentOutputChanged_TriggersUpdate()
        {
            // Arrange
            await RunOnForegroundAsync(() => ProjectManager.ProjectAdded(Project1));
            var mre = new ManualResetEventSlim(initialState: false);
            var workspaceStateGenerator = new Mock<OmniSharpProjectWorkspaceStateGenerator>();
            workspaceStateGenerator.Setup(generator => generator.Update(It.IsAny<Project>(), It.IsAny<OmniSharpProjectSnapshot>()))
                .Callback<Project, OmniSharpProjectSnapshot>((_, __) => mre.Set());
            var refreshTrigger = CreateRefreshTrigger(workspaceStateGenerator.Object);
            var args = new RazorFileChangeEventArgs("/path/to/obj/file.cshtml.g.cs", "obj/file.cshtml.g.cs", Project1Instance, RazorFileChangeKind.Added);

            // Act
            refreshTrigger.RazorDoreplacedentOutputChanged(args);

            // replacedert
            var result = mre.Wait(WaitDelay);
            replacedert.True(result);
        }

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

[Fact]
        public async Task RazorDoreplacedentOutputChanged_BatchesUpdates()
        {
            // Arrange
            await RunOnForegroundAsync(() => ProjectManager.ProjectAdded(Project1));
            var mre = new ManualResetEventSlim(initialState: false);
            var workspaceStateGenerator = new Mock<OmniSharpProjectWorkspaceStateGenerator>();
            workspaceStateGenerator.Setup(generator => generator.Update(It.IsAny<Project>(), It.IsAny<OmniSharpProjectSnapshot>()))
                .Callback<Project, OmniSharpProjectSnapshot>((_, __) =>
                {
                    if (mre.IsSet)
                    {
                        throw new XunitException("Should not have been called twice.");
                    }

                    mre.Set();
                });
            var refreshTrigger = CreateRefreshTrigger(workspaceStateGenerator.Object, enqueueDelay: 10);
            var args = new RazorFileChangeEventArgs("/path/to/obj/file.cshtml.g.cs", "obj/file.cshtml.g.cs", Project1Instance, RazorFileChangeKind.Added);

            // Act
            refreshTrigger.RazorDoreplacedentOutputChanged(args);
            refreshTrigger.RazorDoreplacedentOutputChanged(args);
            refreshTrigger.RazorDoreplacedentOutputChanged(args);
            refreshTrigger.RazorDoreplacedentOutputChanged(args);

            // replacedert
            var result = mre.Wait(WaitDelay);
            replacedert.True(result);
        }

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

public void MessageReceived(object message)
        {
            Stats.Add(message);
            Received.Add(message);
            if (_waitForReceived is not null && _waitForReceived(message))
                Reset.Set();
        }

19 Source : CommonApplicationLogic.cs
with MIT License
from azist

protected void NotifyPendingStopOrShutdown()
    {
      var wait = m_ShutdownEvent;
      if (wait != null)
      {
        if (!wait.IsSet) wait.Set();
      }
    }

19 Source : Program.cs
with MIT License
from Azure

public static async Task RunWithNotifications(
            string databaseId,
            CosmosClient client)
        {
            await Program.InitializeAsync(databaseId, client);

            Container leaseContainer = client.GetContainer(databaseId, Program.leasesContainer);
            Container monitoredContainer = client.GetContainer(databaseId, Program.monitoredContainer);

            ManualResetEventSlim manualResetEventSlim = new ManualResetEventSlim();
            Container.ChangeFeedHandler<ToDoItem> handleChanges = (ChangeFeedProcessorContext context, IReadOnlyCollection<ToDoItem> changes, CancellationToken cancellationToken) =>
            {
                Console.WriteLine($"Started handling changes for lease {context.LeaseToken} but throwing an exception to bubble to notifications.");
                manualResetEventSlim.Set();
                throw new Exception("This is an unhandled exception from inside the delegate");
            };

            // <StartWithNotifications>
            Container.ChangeFeedMonitorLeaseAcquireDelegate onLeaseAcquiredAsync = (string leaseToken) =>
            {
                Console.WriteLine($"Lease {leaseToken} is acquired and will start processing");
                return Task.CompletedTask;
            };

            Container.ChangeFeedMonitorLeaseReleaseDelegate onLeaseReleaseAsync = (string leaseToken) =>
            {
                Console.WriteLine($"Lease {leaseToken} is released and processing is stopped");
                return Task.CompletedTask;
            };

            Container.ChangeFeedMonitorErrorDelegate onErrorAsync = (string LeaseToken, Exception exception) =>
            {
                if (exception is ChangeFeedProcessorUserException userException)
                {
                    Console.WriteLine($"Lease {LeaseToken} processing failed with unhandled exception from user delegate {userException.InnerException}");
                }
                else
                {
                    Console.WriteLine($"Lease {LeaseToken} failed with {exception}");
                }

                return Task.CompletedTask;
            };

            ChangeFeedProcessor changeFeedProcessor = monitoredContainer
                .GetChangeFeedProcessorBuilder<ToDoItem>("changeFeedNotifications", handleChanges)
                    .WithLeaseAcquireNotification(onLeaseAcquiredAsync)
                    .WithLeaseReleaseNotification(onLeaseReleaseAsync)
                    .WithErrorNotification(onErrorAsync)
                    .WithInstanceName("consoleHost")
                    .WithLeaseContainer(leaseContainer)
                    .Build();
            // </StartWithNotifications>

            Console.WriteLine($"Starting Change Feed Processor with logging enabled...");
            await changeFeedProcessor.StartAsync();
            Console.WriteLine("Change Feed Processor started.");
            Console.WriteLine("Generating 10 items that will be picked up by the delegate...");
            await Program.GenerateItems(10, client.GetContainer(databaseId, Program.monitoredContainer));
            // Wait random time for the delegate to output all messages after initialization is done
            manualResetEventSlim.Wait();
            await Task.Delay(1000);
            await changeFeedProcessor.StopAsync();
        }

19 Source : Program.cs
with MIT License
from Azure

public static async Task<int> MainAsync(IConfiguration configuration)
        {
            // Bring up the logger before anything else so we can log errors ASAP
            ILogger logger = SetupLogger(configuration);

            logger.LogInformation("Initializing Edge Agent.");

            VersionInfo versionInfo = VersionInfo.Get(VersionInfoFileName);
            if (versionInfo != VersionInfo.Empty)
            {
                logger.LogInformation($"Version - {versionInfo.ToString(true)}");
            }

            LogLogo(logger);

            string mode;

            string configSourceConfig;
            string backupConfigFilePath;
            int maxRestartCount;
            TimeSpan intensiveCareTime;
            int coolOffTimeUnitInSeconds;
            bool usePersistentStorage;
            string storagePath;
            bool enableNonPersistentStorageBackup;
            Option<string> storageBackupPath = Option.None<string>();
            string edgeDeviceHostName;
            string dockerLoggingDriver;
            Dictionary<string, string> dockerLoggingOptions;
            IEnumerable<global::Docker.DotNet.Models.AuthConfig> dockerAuthConfig;
            int configRefreshFrequencySecs;
            ExperimentalFeatures experimentalFeatures;
            MetricsConfig metricsConfig;
            DiagnosticConfig diagnosticConfig;
            bool useServerHeartbeat;

            try
            {
                mode = configuration.GetValue(Constants.ModeKey, "docker");
                configSourceConfig = configuration.GetValue<string>("ConfigSource");
                backupConfigFilePath = configuration.GetValue<string>("BackupConfigFilePath");
                maxRestartCount = configuration.GetValue<int>("MaxRestartCount");
                intensiveCareTime = TimeSpan.FromMinutes(configuration.GetValue<int>("IntensiveCareTimeInMinutes"));
                coolOffTimeUnitInSeconds = configuration.GetValue("CoolOffTimeUnitInSeconds", 10);
                usePersistentStorage = configuration.GetValue("UsePersistentStorage", true);
                useServerHeartbeat = configuration.GetValue("UseServerHeartbeat", true);

                // Note: Keep in sync with iotedge-check's edge-agent-storage-mounted-from-host check (edgelet/iotedge/src/check/checks/storage_mounted_from_host.rs)
                storagePath = GetOrCreateDirectoryPath(configuration.GetValue<string>("StorageFolder"), EdgeAgentStorageFolder);
                enableNonPersistentStorageBackup = configuration.GetValue("EnableNonPersistentStorageBackup", false);

                if (enableNonPersistentStorageBackup)
                {
                    storageBackupPath = Option.Some(GetOrCreateDirectoryPath(configuration.GetValue<string>("BackupFolder"), EdgeAgentStorageBackupFolder));
                }

                backupConfigFilePath = GetFullBackupFilePath(storagePath, backupConfigFilePath);

                edgeDeviceHostName = configuration.GetValue<string>(Constants.EdgeDeviceHostNameKey);
                dockerLoggingDriver = configuration.GetValue<string>("DockerLoggingDriver");
                dockerLoggingOptions = configuration.GetSection("DockerLoggingOptions").Get<Dictionary<string, string>>() ?? new Dictionary<string, string>();
                dockerAuthConfig = configuration.GetSection("DockerRegistryAuth").Get<List<global::Docker.DotNet.Models.AuthConfig>>() ?? new List<global::Docker.DotNet.Models.AuthConfig>();

                NestedEdgeParentUriParser parser = new NestedEdgeParentUriParser();
                dockerAuthConfig = dockerAuthConfig.Select(c =>
                {
                    c.Preplacedword = parser.ParseURI(c.Preplacedword).GetOrElse(c.Preplacedword);
                    return c;
                })
                .ToList();

                configRefreshFrequencySecs = configuration.GetValue("ConfigRefreshFrequencySecs", 3600);
            }
            catch (Exception ex)
            {
                logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error reading the Agent's configuration.");
                return 1;
            }

            IContainer container;
            try
            {
                var builder = new ContainerBuilder();
                builder.RegisterModule(new LoggingModule(dockerLoggingDriver, dockerLoggingOptions));
                string productInfo =
                    versionInfo != VersionInfo.Empty ?
                    $"{Constants.IoTEdgeAgentProductInfoIdentifier}/{versionInfo}" :
                    Constants.IoTEdgeAgentProductInfoIdentifier;
                Option<UpstreamProtocol> upstreamProtocol = configuration.GetValue<string>(Constants.UpstreamProtocolKey).ToUpstreamProtocol();
                Option<IWebProxy> proxy = Proxy.Parse(configuration.GetValue<string>("https_proxy"), logger);
                bool closeOnIdleTimeout = configuration.GetValue(Constants.CloseOnIdleTimeout, false);
                int idleTimeoutSecs = configuration.GetValue(Constants.IdleTimeoutSecs, 300);
                TimeSpan idleTimeout = TimeSpan.FromSeconds(idleTimeoutSecs);
                experimentalFeatures = ExperimentalFeatures.Create(configuration.GetSection("experimentalFeatures"), logger);
                Option<ulong> storageTotalMaxWalSize = GetConfigIfExists<ulong>(Constants.StorageMaxTotalWalSize, configuration, logger);
                Option<ulong> storageMaxManifestFileSize = GetConfigIfExists<ulong>(Constants.StorageMaxManifestFileSize, configuration, logger);
                Option<int> storageMaxOpenFiles = GetConfigIfExists<int>(Constants.StorageMaxOpenFiles, configuration, logger);
                Option<StorageLogLevel> storageLogLevel = GetConfigIfExists<StorageLogLevel>(Constants.StorageLogLevel, configuration, logger);
                string iothubHostname;
                string deviceId;
                string apiVersion = "2018-06-28";
                Option<X509Certificate2> manifestTrustBundle = Option.None<X509Certificate2>();

                switch (mode.ToLowerInvariant())
                {
                    case Constants.DockerMode:
                        var dockerUri = new Uri(configuration.GetValue<string>("DockerUri"));
                        string deviceConnectionString = configuration.GetValue<string>("DeviceConnectionString");
                        IotHubConnectionStringBuilder connectionStringParser = IotHubConnectionStringBuilder.Create(deviceConnectionString);
                        deviceId = connectionStringParser.DeviceId;
                        iothubHostname = connectionStringParser.HostName;
                        builder.RegisterModule(new AgentModule(maxRestartCount, intensiveCareTime, coolOffTimeUnitInSeconds, usePersistentStorage, storagePath, enableNonPersistentStorageBackup, storageBackupPath, storageTotalMaxWalSize, storageMaxManifestFileSize, storageMaxOpenFiles, storageLogLevel));
                        builder.RegisterModule(new DockerModule(deviceConnectionString, edgeDeviceHostName, dockerUri, dockerAuthConfig, upstreamProtocol, proxy, productInfo, closeOnIdleTimeout, idleTimeout, useServerHeartbeat, backupConfigFilePath));
                        break;

                    case Constants.IotedgedMode:
                        string managementUri = configuration.GetValue<string>(Constants.EdgeletManagementUriVariableName);
                        string workloadUri = configuration.GetValue<string>(Constants.EdgeletWorkloadUriVariableName);
                        iothubHostname = configuration.GetValue<string>(Constants.IotHubHostnameVariableName);
                        deviceId = configuration.GetValue<string>(Constants.DeviceIdVariableName);
                        string moduleId = configuration.GetValue(Constants.ModuleIdVariableName, Constants.EdgeAgentModuleIdenreplacedyName);
                        string moduleGenerationId = configuration.GetValue<string>(Constants.EdgeletModuleGenerationIdVariableName);
                        apiVersion = configuration.GetValue<string>(Constants.EdgeletApiVersionVariableName);
                        TimeSpan performanceMetricsUpdateFrequency = configuration.GetTimeSpan("PerformanceMetricsUpdateFrequency", TimeSpan.FromMinutes(5));
                        builder.RegisterModule(new AgentModule(maxRestartCount, intensiveCareTime, coolOffTimeUnitInSeconds, usePersistentStorage, storagePath, Option.Some(new Uri(workloadUri)), Option.Some(apiVersion), moduleId, Option.Some(moduleGenerationId), enableNonPersistentStorageBackup, storageBackupPath, storageTotalMaxWalSize, storageMaxManifestFileSize, storageMaxOpenFiles, storageLogLevel));
                        builder.RegisterModule(new EdgeletModule(iothubHostname, deviceId, new Uri(managementUri), new Uri(workloadUri), apiVersion, dockerAuthConfig, upstreamProtocol, proxy, productInfo, closeOnIdleTimeout, idleTimeout, performanceMetricsUpdateFrequency, useServerHeartbeat, backupConfigFilePath));
                        IEnumerable<X509Certificate2> trustBundle =
                            await CertificateHelper.GetTrustBundleFromEdgelet(new Uri(workloadUri), apiVersion, Constants.WorkloadApiVersion, moduleId, moduleGenerationId);
                        CertificateHelper.InstallCertificates(trustBundle, logger);
                        manifestTrustBundle = await CertificateHelper.GetManifestTrustBundleFromEdgelet(new Uri(workloadUri), apiVersion, Constants.WorkloadApiVersion, moduleId, moduleGenerationId);

                        break;

                    case Constants.KubernetesMode:
                        managementUri = configuration.GetValue<string>(Constants.EdgeletManagementUriVariableName);
                        workloadUri = configuration.GetValue<string>(Constants.EdgeletWorkloadUriVariableName);
                        moduleId = configuration.GetValue(Constants.ModuleIdVariableName, Constants.EdgeAgentModuleIdenreplacedyName);
                        moduleGenerationId = configuration.GetValue<string>(Constants.EdgeletModuleGenerationIdVariableName);
                        apiVersion = configuration.GetValue<string>(Constants.EdgeletApiVersionVariableName);
                        iothubHostname = configuration.GetValue<string>(Constants.IotHubHostnameVariableName);
                        deviceId = configuration.GetValue<string>(Constants.DeviceIdVariableName);
                        string proxyImage = configuration.GetValue<string>(K8sConstants.ProxyImageEnvKey);
                        Option<string> proxyImagePullSecretName = Option.Maybe(configuration.GetValue<string>(K8sConstants.ProxyImagePullSecretNameEnvKey));
                        string proxyConfigPath = configuration.GetValue<string>(K8sConstants.ProxyConfigPathEnvKey);
                        string proxyConfigVolumeName = configuration.GetValue<string>(K8sConstants.ProxyConfigVolumeEnvKey);
                        string proxyConfigMapName = configuration.GetValue<string>(K8sConstants.ProxyConfigMapNameEnvKey);
                        string proxyTrustBundlePath = configuration.GetValue<string>(K8sConstants.ProxyTrustBundlePathEnvKey);
                        string proxyTrustBundleVolumeName = configuration.GetValue<string>(K8sConstants.ProxyTrustBundleVolumeEnvKey);
                        string proxyTrustBundleConfigMapName = configuration.GetValue<string>(K8sConstants.ProxyTrustBundleConfigMapEnvKey);
                        PortMapServiceType mappedServiceDefault = GetDefaultServiceType(configuration);
                        bool enableServiceCallTracing = configuration.GetValue<bool>(K8sConstants.EnableK8sServiceCallTracingName);
                        bool useMountSourceForVolumeName = configuration.GetValue<bool>(K8sConstants.UseMountSourceForVolumeNameKey, false);
                        string storageClreplacedName = configuration.GetValue<string>(K8sConstants.StorageClreplacedNameKey);
                        Option<uint> persistentVolumeClaimDefaultSizeMb = Option.Maybe(configuration.GetValue<uint?>(K8sConstants.PersistentVolumeClaimDefaultSizeInMbKey));
                        string deviceNamespace = configuration.GetValue<string>(K8sConstants.K8sNamespaceKey);
                        var kubernetesExperimentalFeatures = KubernetesExperimentalFeatures.Create(configuration.GetSection("experimentalFeatures"), logger);
                        var moduleOwner = new KubernetesModuleOwner(
                            configuration.GetValue<string>(K8sConstants.EdgeK8sObjectOwnerApiVersionKey),
                            configuration.GetValue<string>(K8sConstants.EdgeK8sObjectOwnerKindKey),
                            configuration.GetValue<string>(K8sConstants.EdgeK8sObjectOwnerNameKey),
                            configuration.GetValue<string>(K8sConstants.EdgeK8sObjectOwnerUidKey));
                        bool runAsNonRoot = configuration.GetValue<bool>(K8sConstants.RunAsNonRootKey);

                        builder.RegisterModule(new AgentModule(maxRestartCount, intensiveCareTime, coolOffTimeUnitInSeconds, usePersistentStorage, storagePath, Option.Some(new Uri(workloadUri)), Option.Some(apiVersion), moduleId, Option.Some(moduleGenerationId), enableNonPersistentStorageBackup, storageBackupPath, storageTotalMaxWalSize, storageMaxManifestFileSize, storageMaxOpenFiles, storageLogLevel));
                        builder.RegisterModule(
                            new KubernetesModule(
                                iothubHostname,
                                deviceId,
                                edgeDeviceHostName,
                                proxyImage,
                                proxyImagePullSecretName,
                                proxyConfigPath,
                                proxyConfigVolumeName,
                                proxyConfigMapName,
                                proxyTrustBundlePath,
                                proxyTrustBundleVolumeName,
                                proxyTrustBundleConfigMapName,
                                apiVersion,
                                deviceNamespace,
                                new Uri(managementUri),
                                new Uri(workloadUri),
                                dockerAuthConfig,
                                upstreamProtocol,
                                Option.Some(productInfo),
                                mappedServiceDefault,
                                enableServiceCallTracing,
                                useMountSourceForVolumeName,
                                storageClreplacedName,
                                persistentVolumeClaimDefaultSizeMb,
                                proxy,
                                closeOnIdleTimeout,
                                idleTimeout,
                                useServerHeartbeat,
                                kubernetesExperimentalFeatures,
                                moduleOwner,
                                runAsNonRoot));

                        IEnumerable<X509Certificate2> k8sTrustBundle = await CertificateHelper.GetTrustBundleFromEdgelet(new Uri(workloadUri), apiVersion, Constants.WorkloadApiVersion, moduleId, moduleGenerationId);
                        CertificateHelper.InstallCertificates(k8sTrustBundle, logger);

                        break;

                    default:
                        throw new InvalidOperationException($"Mode '{mode}' not supported.");
                }

                switch (configSourceConfig.ToLowerInvariant())
                {
                    case "twin":
                        bool enableStreams = configuration.GetValue(Constants.EnableStreams, false);
                        int requestTimeoutSecs = configuration.GetValue(Constants.RequestTimeoutSecs, 600);
                        builder.RegisterModule(
                            new TwinConfigSourceModule(
                                iothubHostname,
                                deviceId,
                                configuration,
                                versionInfo,
                                TimeSpan.FromSeconds(configRefreshFrequencySecs),
                                enableStreams,
                                TimeSpan.FromSeconds(requestTimeoutSecs),
                                experimentalFeatures,
                                manifestTrustBundle));
                        break;

                    case "local":
                        string localConfigFilePath = GetLocalConfigFilePath(configuration, logger);
                        builder.RegisterModule(new FileConfigSourceModule(localConfigFilePath, configuration, versionInfo));
                        break;

                    default:
                        throw new InvalidOperationException($"ConfigSource '{configSourceConfig}' not supported.");
                }

                metricsConfig = new MetricsConfig(configuration);
                builder.RegisterModule(new MetricsModule(metricsConfig, iothubHostname, deviceId));

                bool diagnosticsEnabled = configuration.GetValue("SendRuntimeQualityTelemetry", true);
                diagnosticConfig = new DiagnosticConfig(diagnosticsEnabled, storagePath, configuration);
                builder.RegisterModule(new DiagnosticsModule(diagnosticConfig));

                container = builder.Build();
            }
            catch (Exception ex)
            {
                logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error building application.");
                return 1;
            }

            // TODO move this code to Agent
            if (mode.ToLowerInvariant().Equals(Constants.KubernetesMode))
            {
                // Block agent startup routine until proxy sidecar container is ready
                string managementUri = configuration.GetValue<string>(Constants.EdgeletManagementUriVariableName);
                string apiVersion = configuration.GetValue<string>(Constants.EdgeletApiVersionVariableName);
                ProxyReadinessProbe probe = new ProxyReadinessProbe(new Uri(managementUri), apiVersion);

                CancellationTokenSource tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(5));
                await probe.WaitUntilProxyIsReady(tokenSource.Token);

                // Start environment operator
                IKubernetesEnvironmentOperator environmentOperator = container.Resolve<IKubernetesEnvironmentOperator>();
                environmentOperator.Start();

                // Start the edge deployment operator
                IEdgeDeploymentOperator edgeDeploymentOperator = container.Resolve<IEdgeDeploymentOperator>();
                edgeDeploymentOperator.Start();
            }

            // Initialize metrics
            if (metricsConfig.Enabled)
            {
                container.Resolve<IMetricsListener>().Start(logger);
                container.Resolve<ISystemResourcesMetrics>().Start(logger);
                await container.Resolve<MetadataMetrics>().Start(logger, versionInfo.ToString(true), Newtonsoft.Json.JsonConvert.SerializeObject(experimentalFeatures));
            }

            // Initialize metric uploading
            if (diagnosticConfig.Enabled)
            {
                MetricsWorker worker = await container.Resolve<Task<MetricsWorker>>();
                worker.Start(diagnosticConfig.ScrapeInterval, diagnosticConfig.UploadInterval);
                Console.WriteLine($"Scraping frequency: {diagnosticConfig.ScrapeInterval}\nUpload Frequency: {diagnosticConfig.UploadInterval}");
            }

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler)
                = ShutdownHandler.Init(ShutdownWaitPeriod, logger);

            // Register request handlers
            await RegisterRequestHandlers(container);

            // Initialize stream request listener
            IStreamRequestListener streamRequestListener = await container.Resolve<Task<IStreamRequestListener>>();
            streamRequestListener.InitPump();

            int returnCode;
            using (IConfigSource unused = await container.Resolve<Task<IConfigSource>>())
            {
                Option<Agent> agentOption = Option.None<Agent>();

                try
                {
                    Agent agent = await container.Resolve<Task<Agent>>();
                    agentOption = Option.Some(agent);
                    while (!cts.Token.IsCancellationRequested)
                    {
                        try
                        {
                            await agent.ReconcileAsync(cts.Token).TimeoutAfter(ReconcileTimeout);
                        }
                        catch (Exception ex) when (!ex.IsFatal())
                        {
                            logger.LogWarning(AgentEventIds.Agent, ex, "Agent reconcile concluded with errors.");
                        }

                        await Task.Delay(TimeSpan.FromSeconds(5), cts.Token);
                    }

                    logger.LogInformation("Closing module management agent.");

                    returnCode = 0;
                }
                catch (OperationCanceledException)
                {
                    logger.LogInformation("Main thread terminated");
                    returnCode = 0;
                }
                catch (Exception ex)
                {
                    logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error starting Agent.");
                    returnCode = 1;
                }

                // Attempt to report shutdown of Agent
                await Cleanup(agentOption, logger);
                await CloseDbStoreProviderAsync(container);

                if (metricsConfig.Enabled && returnCode == 0)
                {
                    container.Resolve<IDeploymentMetrics>().IndicateCleanShutdown();
                }

                completed.Set();
            }

            handler.ForEach(h => GC.KeepAlive(h));
            return returnCode;
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task<int> MainAsync(IConfigurationRoot configuration)
        {
            string logLevel = configuration.GetValue($"{Logger.RuntimeLogLevelEnvKey}", "info");
            Logger.SetLogLevel(logLevel);

            // Set the LoggerFactory used by the Routing code.
            if (configuration.GetValue("EnableRoutingLogging", false))
            {
                Routing.LoggerFactory = Logger.Factory;
            }

            ILogger logger = Logger.Factory.CreateLogger("EdgeHub");

            EdgeHubCertificates certificates = await EdgeHubCertificates.LoadAsync(configuration, logger);
            bool clientCertAuthEnabled = configuration.GetValue(Constants.ConfigKey.EdgeHubClientCertAuthEnabled, false);

            string sslProtocolsConfig = configuration.GetValue(Constants.ConfigKey.SslProtocols, string.Empty);
            SslProtocols sslProtocols = SslProtocolsHelper.Parse(sslProtocolsConfig, DefaultSslProtocols, logger);
            logger.LogInformation($"Enabling SSL protocols: {sslProtocols.Print()}");

            IDependencyManager dependencyManager = new DependencyManager(configuration, certificates.ServerCertificate, certificates.TrustBundle, certificates.ManifestTrustBundle, sslProtocols);
            Hosting hosting = Hosting.Initialize(configuration, certificates.ServerCertificate, dependencyManager, clientCertAuthEnabled, sslProtocols);
            IContainer container = hosting.Container;

            logger.LogInformation("Initializing Edge Hub");
            LogLogo(logger);
            LogVersionInfo(logger);
            logger.LogInformation($"OptimizeForPerformance={configuration.GetValue("OptimizeForPerformance", true)}");
            logger.LogInformation($"MessageAckTimeoutSecs={configuration.GetValue("MessageAckTimeoutSecs", 30)}");
            logger.LogInformation("Loaded server certificate with expiration date of {0}", certificates.ServerCertificate.NotAfter.ToString("o"));

            var metricsProvider = container.Resolve<IMetricsProvider>();
            Metrics.InitWithAspNet(metricsProvider, logger); // Note this requires App.UseMetricServer() to be called in Startup.cs

            // EdgeHub and CloudConnectionProvider have a circular dependency. So need to Bind the EdgeHub to the CloudConnectionProvider.
            IEdgeHub edgeHub = await container.Resolve<Task<IEdgeHub>>();
            ICloudConnectionProvider cloudConnectionProvider = await container.Resolve<Task<ICloudConnectionProvider>>();
            cloudConnectionProvider.BindEdgeHub(edgeHub);

            // EdgeHub cloud proxy and DeviceConnectivityManager have a circular dependency,
            // so the cloud proxy has to be set on the DeviceConnectivityManager after both have been initialized.
            var deviceConnectivityManager = container.Resolve<IDeviceConnectivityManager>();
            IConnectionManager connectionManager = await container.Resolve<Task<IConnectionManager>>();
            (deviceConnectivityManager as DeviceConnectivityManager)?.SetConnectionManager(connectionManager);

            // Register EdgeHub credentials
            var edgeHubCredentials = container.ResolveNamed<IClientCredentials>("EdgeHubCredentials");
            ICredentialsCache credentialsCache = await container.Resolve<Task<ICredentialsCache>>();
            await credentialsCache.Add(edgeHubCredentials);

            // Register EdgeHub indenreplacedy in device scopes cache.
            // When we connect upstream, we verify that idenreplacedy is in scope.
            // On a fresh start, we may not yet received the scopes from the upstream, so we need
            // to force add edgeHub in the cache so it is able to connect upstream.
            // Once we get the scopes from the upstream, this record is replaced.
            ServiceIdenreplacedy edgeHubIdenreplacedy = container.ResolveNamed<ServiceIdenreplacedy>("EdgeHubIdenreplacedy");
            IServiceIdenreplacedyHierarchy idenreplacedyScopes = container.Resolve<IServiceIdenreplacedyHierarchy>();
            await idenreplacedyScopes.AddOrUpdate(edgeHubIdenreplacedy);

            // Initializing configuration
            logger.LogInformation("Initializing configuration");
            IConfigSource configSource = await container.Resolve<Task<IConfigSource>>();
            ConfigUpdater configUpdater = await container.Resolve<Task<ConfigUpdater>>();
            ExperimentalFeatures experimentalFeatures = CreateExperimentalFeatures(configuration);
            var configUpdaterStartupFailed = new TaskCompletionSource<bool>();
            var configDownloadTask = configUpdater.Init(configSource);

            _ = configDownloadTask.ContinueWith(
                                            _ => configUpdaterStartupFailed.SetResult(false),
                                            TaskContinuationOptions.OnlyOnFaulted);

            if (!Enum.TryParse(configuration.GetValue("AuthenticationMode", string.Empty), true, out AuthenticationMode authenticationMode)
                || authenticationMode != AuthenticationMode.Cloud)
            {
                ConnectionReauthenticator connectionReauthenticator = await container.Resolve<Task<ConnectionReauthenticator>>();
                connectionReauthenticator.Init();
            }

            TimeSpan shutdownWaitPeriod = TimeSpan.FromSeconds(configuration.GetValue("ShutdownWaitPeriod", DefaultShutdownWaitPeriod));
            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(shutdownWaitPeriod, logger);

            using (IProtocolHead mqttBrokerProtocolHead = await GetMqttBrokerProtocolHeadAsync(experimentalFeatures, container))
            using (IProtocolHead edgeHubProtocolHead = await GetEdgeHubProtocolHeadAsync(logger, configuration, experimentalFeatures, container, hosting))
            using (var renewal = new CertificateRenewal(certificates, logger))
            {
                try
                {
                    await Task.WhenAll(mqttBrokerProtocolHead.StartAsync(), configDownloadTask);
                    await edgeHubProtocolHead.StartAsync();
                    await Task.WhenAny(cts.Token.WhenCanceled(), renewal.Token.WhenCanceled(), configUpdaterStartupFailed.Task);
                }
                catch (Exception ex)
                {
                    logger.LogError($"Error starting protocol heads: {ex.Message}");
                }

                logger.LogInformation("Stopping the protocol heads...");
                await Task.WhenAll(mqttBrokerProtocolHead.CloseAsync(CancellationToken.None), edgeHubProtocolHead.CloseAsync(CancellationToken.None));
                logger.LogInformation("Protocol heads stopped.");

                await CloseDbStoreProviderAsync(container);
            }

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            logger.LogInformation("Shutdown complete.");
            return 0;
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task<int> MainAsync()
        {
            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            Logger.LogInformation($"Starting metrics collector with the following settings:\r\n{Settings.Current}");

            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);
            ITransportSettings[] transportSettings = { mqttSetting };
            ModuleClient moduleClient = null;
            try
            {
                moduleClient = await ModuleClient.CreateFromEnvironmentAsync(transportSettings);
                Option<SortedDictionary<string, string>> additionalTags = await GetAdditionalTagsFromTwin(moduleClient);

                MetricsScraper scraper = new MetricsScraper(Settings.Current.Endpoints);
                IMetricsPublisher publisher;
                if (Settings.Current.UploadTarget == UploadTarget.AzureLogreplacedytics)
                {
                    publisher = new LogreplacedyticsUpload(Settings.Current.LogreplacedyticsWorkspaceId, Settings.Current.LogreplacedyticsWorkspaceKey, Settings.Current.LogreplacedyticsLogType);
                }
                else
                {
                    publisher = new IotHubMetricsUpload(moduleClient, Settings.Current.MessageIdentifier);
                }

                using (MetricsScrapeAndUpload metricsScrapeAndUpload = new MetricsScrapeAndUpload(scraper, publisher, additionalTags))
                {
                    TimeSpan scrapeAndUploadInterval = TimeSpan.FromSeconds(Settings.Current.ScrapeFrequencySecs);
                    metricsScrapeAndUpload.Start(scrapeAndUploadInterval);
                    await cts.Token.WhenCanceled();
                }
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error occurred during metrics collection setup.");
            }
            finally
            {
                moduleClient?.Dispose();
            }

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));

            Logger.LogInformation("MetricsCollector Main() finished.");
            return 0;
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task<int> MainAsync()
        {
            Console.WriteLine("SimulatedTemperatureSensor Main() started.");

            IConfiguration configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("config/appsettings.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

            messageDelay = configuration.GetValue("MessageDelay", TimeSpan.FromSeconds(5));
            int messageCount = configuration.GetValue(MessageCountConfigKey, 500);
            var simulatorParameters = new SimulatorParameters
            {
                MachineTempMin = configuration.GetValue<double>("machineTempMin", 21),
                MachineTempMax = configuration.GetValue<double>("machineTempMax", 100),
                MachinePressureMin = configuration.GetValue<double>("machinePressureMin", 1),
                MachinePressureMax = configuration.GetValue<double>("machinePressureMax", 10),
                AmbientTemp = configuration.GetValue<double>("ambientTemp", 21),
                HumidityPercent = configuration.GetValue("ambientHumidity", 25)
            };

            Console.WriteLine(
                $"Initializing simulated temperature sensor to send {(SendUnlimitedMessages(messageCount) ? "unlimited" : messageCount.ToString())} "
                + $"messages, at an interval of {messageDelay.TotalSeconds} seconds.\n"
                + $"To change this, set the environment variable {MessageCountConfigKey} to the number of messages that should be sent (set it to -1 to send unlimited messages).");

            TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only);

            ModuleClient moduleClient = await CreateModuleClientAsync(
                transportType,
                DefaultTimeoutErrorDetectionStrategy,
                DefaultTransientRetryStrategy);
            await moduleClient.OpenAsync();
            await moduleClient.SetMethodHandlerAsync("reset", ResetMethod, null);

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null);

            Twin currentTwinProperties = await moduleClient.GetTwinAsync();
            if (currentTwinProperties.Properties.Desired.Contains(SendIntervalConfigKey))
            {
                messageDelay = TimeSpan.FromSeconds((int)currentTwinProperties.Properties.Desired[SendIntervalConfigKey]);
            }

            if (currentTwinProperties.Properties.Desired.Contains(SendDataConfigKey))
            {
                sendData = (bool)currentTwinProperties.Properties.Desired[SendDataConfigKey];
                if (!sendData)
                {
                    Console.WriteLine("Sending data disabled. Change twin configuration to start sending again.");
                }
            }

            ModuleClient userContext = moduleClient;
            await moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdated, userContext);
            await moduleClient.SetInputMessageHandlerAsync("control", ControlMessageHandle, userContext);
            await SendEvents(moduleClient, messageCount, simulatorParameters, cts);
            await cts.Token.WhenCanceled();

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Console.WriteLine("SimulatedTemperatureSensor Main() finished.");
            return 0;
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task Main(string[] args)
        {
            Logger.LogInformation($"Starting Deployment Tester with the following settings: \r\n{Settings.Current}");

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            var testResultReportingClient = new TestResultReportingClient { BaseUrl = Settings.Current.TestResultCoordinatorUrl.AbsoluteUri };

            try
            {
                if (Settings.Current.TestMode == DeploymentTesterMode.Receiver)
                {
                    await ReportDeploymentEnvironmentVariablesAsync(testResultReportingClient);
                }
                else
                {
                    await Task.Delay(Settings.Current.TestStartDelay);
                    await UpdateDeploymentEnvironmentVariablesAsync(testResultReportingClient, cts);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Unexpected exception found.");
                await ModuleUtil.ReportTestResultAsync(testResultReportingClient, Logger, new ErrorTestResult(Settings.Current.TrackingId, Settings.Current.ModuleId, ex));
            }

            await cts.Token.WhenCanceled();
            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("DeploymentTester Main() finished.");
        }

19 Source : Program.cs
with MIT License
from Azure

public static async Task<int> MainAsync()
        {
            Logger.LogInformation($"Starting DirectMethodSender with the following settings:\r\n{Settings.Current}");

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);
            DirectMethodSenderBase directMethodClient = null;
            ReporterClientBase reportClient = null;

            try
            {
                Guid batchId = Guid.NewGuid();
                Logger.LogInformation($"Batch Id={batchId}");
                Logger.LogInformation($"DirectMethodSender delay start for {Settings.Current.TestStartDelay}.");
                await Task.Delay(Settings.Current.TestStartDelay, cts.Token);

                DateTime testStartAt = DateTime.UtcNow;

                directMethodClient = await CreateClientAsync(Settings.Current.InvocationSource);
                reportClient = ReporterClientBase.Create(
                    Logger,
                    Settings.Current.ReportingEndpointUrl,
                    Settings.Current.TransportType);

                while (!cts.Token.IsCancellationRequested && IsTestTimeUp(testStartAt))
                {
                    await Task.Delay(Settings.Current.DirectMethodFrequency, cts.Token);

                    (HttpStatusCode resultStatusCode, ulong dmCounter) = await directMethodClient.InvokeDirectMethodAsync(Settings.Current.DirectMethodName, cts);
                    DirectMethodResultType resultType = Settings.Current.DirectMethodResultType;

                    if (ShouldReportResults(resultType, resultStatusCode))
                    {
                        // Generate a testResult type depending on the reporting endpoint
                        TestResultBase testResult = ConstructTestResult(
                            resultType,
                            batchId,
                            dmCounter,
                            resultStatusCode);

                        await reportClient.SendTestResultAsync(testResult);
                    }
                }

                await cts.Token.WhenCanceled();
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error occurred during direct method sender test setup");
            }
            finally
            {
                // Implicit CloseAsync()
                directMethodClient?.Dispose();
                reportClient?.Dispose();
            }

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("DirectMethodSender Main() finished.");
            return 0;
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task<int> MainAsync()
        {
            Guid batchId = Guid.NewGuid();
            Logger.LogInformation($"Starting EdgeHubRestartTester ({batchId}) with the following settings:\r\n{Settings.Current}");

            Logger.LogInformation($"EdgeHubRestartTester delay start for {Settings.Current.TestStartDelay}.");
            await Task.Delay(Settings.Current.TestStartDelay);

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            ServiceClient iotHubServiceClient = null;
            List<ModuleClient> moduleClients = new List<ModuleClient>();
            try
            {
                iotHubServiceClient = ServiceClient.CreateFromConnectionString(Settings.Current.IoTHubConnectionString);

                List<IEdgeHubConnectorTest> edgeHubConnectorTests = new List<IEdgeHubConnectorTest>();

                foreach (EdgeHubConnectorsConfig eachConfig in await Settings.Current.GetConnectorConfigAsync())
                {
                    if (eachConfig.MessageOutputEndpoint != null)
                    {
                        ModuleClient msgModuleClient = await ModuleUtil.CreateModuleClientAsync(
                            eachConfig.TransportType,
                            new ClientOptions(),
                            ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                            ModuleUtil.DefaultTransientRetryStrategy,
                            Logger);

                        msgModuleClient.OperationTimeoutInMilliseconds = (uint)Settings.Current.SdkOperationTimeout.TotalMilliseconds;

                        moduleClients.Add(msgModuleClient);
                        edgeHubConnectorTests.Add(
                            new MessageEdgeHubConnectorTest(
                                batchId,
                                Logger,
                                msgModuleClient,
                                eachConfig.MessageOutputEndpoint));
                    }

                    if (eachConfig.DirectMethodTargetModuleId != null)
                    {
                        ModuleClient dmModuleClient = await ModuleUtil.CreateModuleClientAsync(
                            eachConfig.TransportType,
                            new ClientOptions(),
                            ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                            ModuleUtil.DefaultTransientRetryStrategy,
                            Logger);

                        moduleClients.Add(dmModuleClient);
                        edgeHubConnectorTests.Add(
                            new DirectMethodEdgeHubConnectorTest(
                                batchId,
                                Logger,
                                dmModuleClient,
                                eachConfig.DirectMethodTargetModuleId));
                    }
                }

                DateTime testStart = DateTime.UtcNow;
                DateTime testCompletionTime = testStart + Settings.Current.TestDuration;

                while ((!cts.IsCancellationRequested) && (DateTime.UtcNow < testCompletionTime))
                {
                    DateTime restartTime = await RestartEdgeHubAsync(
                        iotHubServiceClient,
                        cts.Token);
                    DateTime eachTestExpirationTime = restartTime.Add(Settings.Current.RestartPeriod);

                    List<Task> taskList = new List<Task>();
                    foreach (IEdgeHubConnectorTest eachConnectorTest in edgeHubConnectorTests)
                    {
                        taskList.Add(
                            eachConnectorTest.StartAsync(
                                eachTestExpirationTime,
                                restartTime,
                                cts.Token));
                    }

                    // Wait for the two task to be done before do a restart
                    await Task.WhenAll(taskList);

                    // Wait until the specified restart period to do another restart
                    TimeSpan waitTime = eachTestExpirationTime - DateTime.UtcNow;
                    if (waitTime.TotalMilliseconds > 0)
                    {
                        await Task.Delay(waitTime, cts.Token);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.LogError($"Exception caught: {e}");
                throw;
            }
            finally
            {
                iotHubServiceClient?.Dispose();

                foreach (ModuleClient client in moduleClients)
                {
                    client.Dispose();
                }
            }

            await cts.Token.WhenCanceled();
            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("EdgeHubRestartTester Main() finished.");
            return 0;
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task Main()
        {
            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Log);

            Log.LogInformation($"Starting with {Settings.Current.NetworkRunProfile.ProfileType} Settings: {Settings.Current.NetworkRunProfile.ProfileSetting}");

            var controllers = new List<INetworkController>();

            try
            {
                var networkInterfaceName = DockerHelper.GetDockerInterfaceName();

                if (networkInterfaceName.HasValue)
                {
                    await networkInterfaceName.ForEachAsync(async name =>
                    {
                        string hubHostname = GetHostnameForExternalTraffic();
                        var offline = new OfflineController(name, hubHostname, Settings.Current.NetworkRunProfile.ProfileSetting);
                        var satellite = new SatelliteController(name, hubHostname, Settings.Current.NetworkRunProfile.ProfileSetting);
                        var cellular = new CellularController(name, hubHostname, Settings.Current.NetworkRunProfile.ProfileSetting);
                        controllers.AddRange(new List<INetworkController> { offline, satellite, cellular });

                        // Reset network status before start delay to ensure network status is in designed state before test starts.
                        var sw = new Stopwatch();
                        sw.Start();
                        await RemoveAllControllingRules(controllers, cts.Token);
                        sw.Stop();
                        TimeSpan durationBeforeTestStart = Settings.Current.StartAfter <= sw.Elapsed ? TimeSpan.Zero : Settings.Current.StartAfter - sw.Elapsed;

                        Log.LogInformation($"Delay {durationBeforeTestStart} before starting network controller.");
                        await Task.Delay(durationBeforeTestStart, cts.Token);

                        switch (Settings.Current.NetworkRunProfile.ProfileType)
                        {
                            case NetworkControllerType.Offline:
                                await StartAsync(offline, cts.Token);
                                break;
                            case NetworkControllerType.Satellite:
                                await StartAsync(satellite, cts.Token);
                                break;
                            case NetworkControllerType.Cellular:
                                await StartAsync(cellular, cts.Token);
                                break;
                            case NetworkControllerType.Online:
                                await SetToggleConnectivityMethod(name, cts.Token);
                                Log.LogInformation($"No restrictions to be set, running as online");
                                break;
                            default:
                                throw new NotSupportedException($"Network type {Settings.Current.NetworkRunProfile.ProfileType} is not supported.");
                        }
                    });
                }
                else
                {
                    Log.LogError($"No network interface found for docker network {Settings.Current.NetworkId}");
                }
            }
            catch (Exception ex)
            {
                Log.LogError(ex, $"Unexpected exception thrown from {nameof(Main)} method");
            }

            await cts.Token.WhenCanceled();
            await CleanupControllingRulesOnShutdown(controllers, CancellationToken.None);
            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
        }

19 Source : Program.cs
with MIT License
from Azure

public static async Task<int> MainAsync()
        {
            Logger.LogInformation($"Starting CloudToDeviceMessageTester with the following settings:\r\n{Settings.Current}");

            DateTime testStartAt = DateTime.UtcNow;

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            ICloudToDeviceMessageTester cloudToDeviceMessageTester = null;
            TestResultReportingClient reportClient = new TestResultReportingClient() { BaseUrl = Settings.Current.ReportingEndpointUrl.AbsoluteUri };
            try
            {
                if (Settings.Current.TestMode == CloudToDeviceMessageTesterMode.Receiver)
                {
                    cloudToDeviceMessageTester = new CloudToDeviceMessageReceiver(
                        Logger,
                        Settings.Current.SharedSettings,
                        Settings.Current.ReceiverSettings,
                        reportClient);
                }
                else
                {
                    cloudToDeviceMessageTester = new CloudToDeviceMessageSender(
                        Logger,
                        Settings.Current.SharedSettings,
                        Settings.Current.SenderSettings,
                        reportClient);
                }

                await cloudToDeviceMessageTester.StartAsync(cts.Token);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"Error occurred during CloudToDeviceMessageTester while in {Settings.Current.TestMode} mode.");
            }
            finally
            {
                // Implicit CloseAsync()
                cloudToDeviceMessageTester?.Dispose();
            }

            await cts.Token.WhenCanceled();
            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation($"{nameof(Program.MainAsync)} finished.");
            return 0;
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task<int> MainAsync()
        {
            DirectMethodReceiver directMethodReceiver = null;

            try
            {
                Logger.LogInformation("DirectMethodReceiver Main() started.");

                (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

                IConfiguration configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("config/appsettings.json", optional: true)
                    .AddEnvironmentVariables()
                    .Build();

                directMethodReceiver = new DirectMethodReceiver(Logger, configuration);

                await directMethodReceiver.InitAsync();

                await cts.Token.WhenCanceled();

                completed.Set();
                handler.ForEach(h => GC.KeepAlive(h));
                Logger.LogInformation("DirectMethodReceiver Main() finished.");
            }
            catch (Exception e)
            {
                Logger.LogError(e.ToString());
            }
            finally
            {
                directMethodReceiver?.Dispose();
            }

            return 0;
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task<int> MainAsync()
        {
            try
            {
                Logger.LogInformation("Validate Metrics Main() started.");

                (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

                IConfiguration configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("config/appsettings.json", optional: true)
                    .AddEnvironmentVariables()
                    .Build();

                var transportType = configuration.GetValue("ClientTransportType", Microsoft.Azure.Devices.Client.TransportType.Mqtt);

                Logger.LogInformation("Make Client");
                using (ModuleClient moduleClient = await ModuleUtil.CreateModuleClientAsync(
                    transportType,
                    new ClientOptions(),
                    ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                    ModuleUtil.DefaultTransientRetryStrategy,
                    Logger))
                using (MetricsScraper scraper = new MetricsScraper(new List<string> { "http://edgeHub:9600/metrics", "http://edgeAgent:9600/metrics" }))
                {
                    Logger.LogInformation("Open Async");
                    await moduleClient.OpenAsync();

                    Logger.LogInformation("Set method handler");
                    await moduleClient.SetMethodHandlerAsync(
                        "ValidateMetrics",
                        async (MethodRequest methodRequest, object _) =>
                        {
                            Logger.LogInformation("Validating metrics");

                            TestReporter testReporter = new TestReporter("Metrics Validation");
                            List<TestBase> tests = new List<TestBase>
                            {
                                new ValidateMessages(testReporter, scraper, moduleClient, transportType),
                                new ValidateDoreplacedentedMetrics(testReporter, scraper, moduleClient),
                                // new ValidateHostRanges(testReporter, scraper, moduleClient),
                            };

                            using (testReporter.MeasureDuration())
                            {
                                await Task.WhenAll(tests.Select(test => test.Start(cts.Token)));
                            }

                            var result = new MethodResponse(Encoding.UTF8.GetBytes(testReporter.ReportResults()), (int)HttpStatusCode.OK);

                            Logger.LogInformation($"Finished validating metrics. Result size: {result.Result.Length}");
                            return result;
                        },
                        null);

                    moduleClient.SetConnectionStatusChangesHandler((status, reason)
                        => Logger.LogWarning($"Module to Edge Hub connection changed Status: {status} Reason: {reason}"));

                    Logger.LogInformation("Ready to validate metrics");
                    await cts.Token.WhenCanceled();
                }

                completed.Set();
                handler.ForEach(h => GC.KeepAlive(h));
                Logger.LogInformation("Validate Metrics Main() finished.");
            }
            catch (Exception e)
            {
                Logger.LogError(e.ToString());
            }

            return 0;
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task<int> MainAsync()
        {
            Logger.LogInformation($"Starting module restarter with the following settings:\r\n{Settings.Current}");

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            await RestartModules(cts);

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("ModuleRestarter Main() finished.");
            return 0;
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task Main()
        {
            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            Logger.LogInformation($"Starting twin tester with the following settings:\r\n{Settings.Current}");

            ITwinTestInitializer twinOperator = null;
            try
            {
                using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Settings.Current.ServiceClientConnectionString))
                {
                    twinOperator = await GetTwinOperatorAsync(registryManager);
                    await twinOperator.StartAsync(cts.Token);
                    await Task.Delay(Settings.Current.TestDuration, cts.Token);

                    Logger.LogInformation($"Test run completed after {Settings.Current.TestDuration}");
                    twinOperator.Stop();

                    await cts.Token.WhenCanceled();
                    completed.Set();
                    handler.ForEach(h => GC.KeepAlive(h));
                    Logger.LogInformation("TwinTester exiting.");
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"Error occurred during twin test setup.");
                twinOperator?.Stop();
            }
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task Main()
        {
            Logger.LogInformation($"Starting load gen with the following settings:\r\n{Settings.Current}");

            ModuleClient moduleClient = null;

            try
            {
                (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

                Guid batchId = Guid.NewGuid();
                Logger.LogInformation($"Batch Id={batchId}");

                ClientOptions options = new ClientOptions();
                Settings.Current.ModelId.ForEach(m => options.ModelId = m);
                moduleClient = await ModuleUtil.CreateModuleClientAsync(
                    Settings.Current.TransportType,
                    options,
                    ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                    ModuleUtil.DefaultTransientRetryStrategy,
                    Logger);

                Logger.LogInformation($"Load gen delay start for {Settings.Current.TestStartDelay}.");
                await Task.Delay(Settings.Current.TestStartDelay);

                LoadGenSenderBase sender;
                switch (Settings.Current.SenderType)
                {
                    case LoadGenSenderType.PriorityMessageSender:
                        sender = new PriorityMessageSender(Logger, moduleClient, batchId, Settings.Current.TrackingId);
                        break;
                    case LoadGenSenderType.DefaultSender:
                    default:
                        sender = new DefaultMessageSender(Logger, moduleClient, batchId, Settings.Current.TrackingId);
                        break;
                }

                DateTime testStartAt = DateTime.UtcNow;
                await sender.RunAsync(cts, testStartAt);

                Logger.LogInformation("Finish sending messages.");
                await cts.Token.WhenCanceled();
                completed.Set();
                handler.ForEach(h => GC.KeepAlive(h));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error occurred during load gen.");
            }
            finally
            {
                Logger.LogInformation("Closing connection to Edge Hub.");
                moduleClient?.CloseAsync();
                moduleClient?.Dispose();
            }

            Logger.LogInformation("Load Gen complete. Exiting.");
        }

19 Source : Program.cs
with MIT License
from Azure

public static void Main()
        {
            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), NullLogger.Instance);

            string countString = Environment.GetEnvironmentVariable("Count");
            int parsedCount = int.Parse(countString);

            for (int i = 0; i < parsedCount; i++)
            {
                Console.WriteLine(i);
            }

            cts.Token.WhenCanceled().Wait();

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task Main(string[] args)
        {
            Logger.LogInformation($"Starting Relayer with the following settings: \r\n{Settings.Current}");
            ModuleClient moduleClient = null;

            try
            {
                moduleClient = await ModuleUtil.CreateModuleClientAsync(
                    Settings.Current.TransportType,
                    new ClientOptions(),
                    ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                    ModuleUtil.DefaultTransientRetryStrategy,
                    Logger);
                DuplicateMessageAuditor duplicateMessageAuditor = new DuplicateMessageAuditor(Settings.Current.MessageDuplicateTolerance);
                MessageHandlerContext messageHandlerContext = new MessageHandlerContext(moduleClient, duplicateMessageAuditor);

                (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

                await SetIsFinishedDirectMethodAsync(moduleClient);

                // Receive a message and call ProcessAndSendMessageAsync to send it on its way
                await moduleClient.SetInputMessageHandlerAsync(Settings.Current.InputName, ProcessAndSendMessageAsync, messageHandlerContext);

                await cts.Token.WhenCanceled();
                completed.Set();
                handler.ForEach(h => GC.KeepAlive(h));
                Logger.LogInformation("Relayer Main() finished.");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error occurred during Relayer.");
            }
            finally
            {
                moduleClient?.CloseAsync();
                moduleClient?.Dispose();
            }
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task<int> MainAsync()
        {
            Logger.LogInformation("TemperatureFilter Main() started.");

            IConfiguration configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("config/appsettings.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

            TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only);

            ModuleClient moduleClient = await ModuleUtil.CreateModuleClientAsync(
                transportType,
                new ClientOptions(),
                ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                ModuleUtil.DefaultTransientRetryStrategy,
                Logger);

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            ModuleConfig moduleConfig = await GetConfigurationAsync(moduleClient);
            Logger.LogInformation($"Using TemperatureThreshold value of {moduleConfig.TemperatureThreshold}");

            var userContext = Tuple.Create(moduleClient, moduleConfig);
            await moduleClient.SetInputMessageHandlerAsync("input1", PrintAndFilterMessages, userContext);

            await cts.Token.WhenCanceled();
            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("TemperatureFilter Main() finished.");
            return 0;
        }

19 Source : Program.cs
with MIT License
from Azure

static async Task Main(string[] args)
        {
            Logger.LogInformation($"Starting TestResultCoordinator with the following settings:\r\n{Settings.Current}");

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            Logger.LogInformation("Creating WebHostBuilder...");
            Task webHost = CreateHostBuilder(args).Build().RunAsync(cts.Token);

            await Task.WhenAny(cts.Token.WhenCanceled(), webHost);

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("TestResultCoordinator Main() exited.");
        }

19 Source : MsalCacheHelperTests.cs
with MIT License
from AzureAD

[TestMethod]
        public void MultiAccessSerialization()
        {
            var cache1 = new MockTokenCache();
            var helper1 = new MsalCacheHelper(
                cache1,
                Storage.Create(_storageCreationPropertiesBuilder.Build(), _logger),
                _logger);

            var cache2 = new MockTokenCache();
            var helper2 = new MsalCacheHelper(
                cache2,
                Storage.Create(_storageCreationPropertiesBuilder.Build(), _logger),
                _logger);

            //Test signalling thread 1
            var resetEvent1 = new ManualResetEventSlim(initialState: false);

            //Test signalling thread 2
            var resetEvent2 = new ManualResetEventSlim(initialState: false);

            //Thread 1 signalling test
            var resetEvent3 = new ManualResetEventSlim(initialState: false);

            // Thread 2 signalling test
            var resetEvent4 = new ManualResetEventSlim(initialState: false);

            var thread1 = new Thread(() =>
            {
                var args = new TokenCacheNotificationArgs(cache1, string.Empty, null, false, false, true, CancellationToken.None);

                helper1.BeforeAccessNotification(args);
                resetEvent3.Set();
                resetEvent1.Wait();
                helper1.AfterAccessNotification(args);
            });

            var thread2 = new Thread(() =>
            {
                var args = new TokenCacheNotificationArgs(cache2, string.Empty, null, false, false, true, CancellationToken.None);
                helper2.BeforeAccessNotification(args);
                resetEvent4.Set();
                resetEvent2.Wait();
                helper2.AfterAccessNotification(args);
                resetEvent4.Set();
            });

            // Let thread 1 start and get the lock
            thread1.Start();
            resetEvent3.Wait();

            // Start thread 2 and give it enough time to get blocked on the lock
            thread2.Start();
            Thread.Sleep(5000);

            // Make sure helper1 has the lock still, and helper2 doesn't
            replacedert.IsNotNull(helper1.CacheLock);
            replacedert.IsNull(helper2.CacheLock);

            // Allow thread1 to give up the lock, and wait for helper2 to get it
            resetEvent1.Set();
            resetEvent4.Wait();
            resetEvent4.Reset();

            // Make sure helper1 gave it up properly, and helper2 now owns the lock
            replacedert.IsNull(helper1.CacheLock);
            replacedert.IsNotNull(helper2.CacheLock);

            // Allow thread2 to give up the lock, and wait for it to complete
            resetEvent2.Set();
            resetEvent4.Wait();

            // Make sure thread2 cleaned up after itself as well
            replacedert.IsNull(helper2.CacheLock);
        }

19 Source : MsalCacheHelperTests.cs
with MIT License
from AzureAD

[TestMethod]
        public void LockTimeoutTest()
        {
            // Total of 1000ms delay
            _storageCreationPropertiesBuilder.CustomizeLockRetry(20, 100);
            var properties = _storageCreationPropertiesBuilder.Build();


            var cache1 = new MockTokenCache();
            var helper1 = new MsalCacheHelper(
                cache1,
                Storage.Create(properties, _logger),
                _logger);

            var cache2 = new MockTokenCache();
            var helper2 = new MsalCacheHelper(
                cache2,
                Storage.Create(properties, _logger),
                _logger);

            //Test signalling thread 1
            var resetEvent1 = new ManualResetEventSlim(initialState: false);

            //Test signalling thread 2
            var resetEvent2 = new ManualResetEventSlim(initialState: false);

            //Thread 1 signalling test
            var resetEvent3 = new ManualResetEventSlim(initialState: false);

            var thread1 = new Thread(() =>
            {
                var args = new TokenCacheNotificationArgs(cache1, string.Empty, null, false, false, true, CancellationToken.None);

                helper1.BeforeAccessNotification(args);
                // Indicate we are waiting
                resetEvent2.Set();
                resetEvent1.Wait();
                helper1.AfterAccessNotification(args);

                // Let thread 1 exit
                resetEvent3.Set();
            });

            Stopwatch getTime = new Stopwatch();

            var thread2 = new Thread(() =>
            {
                var args = new TokenCacheNotificationArgs(cache2, string.Empty, null, false, false, true, CancellationToken.None);
                getTime.Start();
                try
                {

                    helper2.BeforeAccessNotification(args);
                }
                catch (InvalidOperationException)
                {
                    // Invalid operation is the exception thrown if the lock cannot be acquired
                    getTime.Stop();
                }

                resetEvent1.Set();
            });

            // Let thread 1 start and get the lock
            thread1.Start();

            // Wait for thread one to get into the lock
            resetEvent2.Wait();

            // Start thread 2 and give it enough time to get blocked on the lock
            thread2.Start();

            // Wait for the seconf thread to finish
            resetEvent1.Wait();

            replacedert.IsTrue(getTime.ElapsedMilliseconds > 2000);
        }

See More Examples