System.Threading.WaitHandle.WaitOne()

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

2076 Examples 7

19 View Source File : GrpcPeerTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public void EnqueueAnnouncement_ShouldExecuteCallback_Test()
        {
            AutoResetEvent executed = new AutoResetEvent(false);

            NetworkException exception = null;
            var called = false;
            _nonInterceptedPeer.EnqueueAnnouncement(new BlockAnnouncement(), ex =>
            {
                exception = ex;
                called = true;
                executed.Set();
            });

            executed.WaitOne();
            exception.ShouldBeNull();
            called.ShouldBeTrue();
        }

19 View Source File : ParallelLooper.cs
License : The Unlicense
Project Creator : aeroson

public void ForLoop(int beginIndex, int endIndex, Action<int> loopBody)
        {
            //CANNOT CALL THIS WHILE BUSY!!!! replacedUME THAT IS GUARANTEED.
            //Compute intervals for each worker.

            workerCount = workers.Count;

            //TODO: The job splitting could be tuned possibly.
            int iterationCount = endIndex - beginIndex;
            int tasksPerThread = Math.Max(minimumTasksPerThread, iterationCount / maximumIterationsPerTask);
            int taskSubdivisions = workerCount * tasksPerThread;

            currentBeginIndex = beginIndex;
            currentEndIndex = endIndex;
            currentLoopBody = loopBody;
            iterationsPerSteal = Math.Max(1, iterationCount / taskSubdivisions);
            jobIndex = 0;
            float maxJobs = iterationCount / (float) iterationsPerSteal;
            if (maxJobs % 1 == 0)
                maxJobIndex = (int) maxJobs;
            else
                maxJobIndex = 1 + (int) maxJobs;

            for (int i = 0; i < workers.Count; i++)
            {
                workers[i].finalIndex = endIndex;
                workers[i].iterationsPerSteal = iterationsPerSteal;
                workers[i].getToWork.Set();
            }

            loopFinished.WaitOne();
        }

19 View Source File : ThreadPool.cs
License : MIT License
Project Creator : adrenak

private void EnqueueTask(WaitCallback callback, object state) {
            while (m_numTasks == m_taskQueue.Length) {
                m_getNotification.WaitOne();
            }
            m_taskQueue[m_nPutPointer].callback = callback;
            m_taskQueue[m_nPutPointer].args = state;
            ++m_nPutPointer;
            if (m_nPutPointer == m_taskQueue.Length) {
                m_nPutPointer = 0;
            }
#if !UNITY_WEBGL
            if (m_threadPool.Length == 1) {
#endif
                if (Interlocked.Increment(ref m_numTasks) == 1) {
                    m_putNotification.Set();
                }
#if !UNITY_WEBGL
            }
            else {
                Interlocked.Increment(ref m_numTasks);
                m_semapreplaced.Release();
            }
#endif
        }

19 View Source File : KoiInfo.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static void CheckUpdate(ConfuserContext ctx)
        {
            var ver = new KoiSystem().GetVersion(settings.KoiID);
            if(ver == settings.Version)
                return;

            ctx.Logger.LogFormat("New version of KoiVM: {0}", ver);
            ctx.Logger.LogFormat("Current version of KoiVM: {0}", settings.Version);

            if(settings.NoUI)
            {
                ctx.Logger.LogFormat("Updating...");
                var sys = new KoiSystem();
                var hnd = new ManualResetEvent(false);
                var okay = false;
                sys.Progress += _ => { };
                sys.Finish += f =>
                {
                    okay = f;
                    hnd.Set();
                };
                sys.Login(settings.KoiID);
                hnd.WaitOne();
                if(!okay)
                    throw new InvalidOperationException("Authentication failed.");
                settings.Version = ver;
                settings.Save();
            }
            else
            {
                Application.EnableVisualStyles();
                if(new UpdatePrompt(ver) {TopLevel = true}.ShowDialog() != DialogResult.OK)
                    throw new InvalidOperationException("Authentication failed.");
            }
        }

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

private void RunWorkerThread(object threadIndex) {
				WorkerThread workerThread = workerThreads[(int)threadIndex];
				int localJobIndex = 0;

				while(true) {
					// Wait for a task.
					workerThread.TaskWaiting.WaitOne();

					// Exit if task is empty.
					if(LoopFunction == null) {
						return;
					}

					localJobIndex = Interlocked.Increment(ref currentJobIndex);

					while(localJobIndex < stopIndex) {
						////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
						LoopFunction(localJobIndex);
						localJobIndex = Interlocked.Increment(ref currentJobIndex);
					}

					// Signal that thread is idle.
					workerThread.ThreadIdle.Set();
				}
			}

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

public void DoFor(int start, int stop, ForLoopDelegate loopBody) {
                this.currentJobIndex = start - 1;
                this.stopIndex = stop;
                this.LoopFunction = loopBody;

                // Signal waiting task to all threads and mark them not idle.
                for (int i = 0; i < this.threadCount; i++) {
                    WorkerThread workerThread = workerThreads[i];
                    workerThread.ThreadIdle.Reset();
                    workerThread.TaskWaiting.Set();
                }

                // Wait until all threads become idle
                for (int i = 0; i < this.threadCount; i++) {
                    WorkerThread workerThread = workerThreads[i];
                    workerThread.ThreadIdle.WaitOne();
                }
            }

19 View Source File : ThreadTaskManager.cs
License : The Unlicense
Project Creator : aeroson

public void WaitForTaskCompletion()
        {
            //TODO: Try a WAITALL version of this
            if (Interlocked.Decrement(ref tasksRemaining) == 0)
            {
                allThreadsIdleNotifier.Set();
            }
            allThreadsIdleNotifier.WaitOne();

            //When it gets here, it means things are successfully idle'd.
            tasksRemaining = 1;
            allThreadsIdleNotifier.Reset();
        }

19 View Source File : Core.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public void RequestFan1Level(FanLevel? level)
        {
            _requestSemapreplaced.WaitOne();
            _fan1LevelRequested = level;
            _requestSemapreplaced.Release();
        }

19 View Source File : SocketAsyncPool.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public SocketAsyncEventArgs Acquire()
        {
            if (!_acquisitionGate.WaitOne())
                throw new Exception();

            lock (_pool)
            {
                return _pool.Pop();
            }
        }

19 View Source File : Core.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private void BackgroundThread()
        {
            _state.WaitOne();
            _state.BackgroundThreadRunning = true;
            _state.Release();

            bool releaseSemapreplaced = false;

            try
            {
                if (_state.EcFanControlEnabled && IsAutomaticFanControlDisableSupported)
                {
                    _fanController.EnableAutomaticFanControl();
                    Log.Write("Enabled EC fan control – startup");
                }

                while (_state.BackgroundThreadRunning)
                {
                    _state.WaitOne();
                    _requestSemapreplaced.WaitOne();
                    releaseSemapreplaced = true;

                    // Update state.
                    _state.Update();

                    // Take action based on configuration.
                    if (_state.OperationMode == OperationMode.Automatic)
                    {
                        if (!_state.EcFanControlEnabled && IsAutomaticFanControlDisableSupported)
                        {
                            _state.EcFanControlEnabled = true;
                            _fanController.EnableAutomaticFanControl();
                            Log.Write("Enabled EC fan control – automatic mode");
                        }
                    }
                    else if (_state.OperationMode == OperationMode.Manual && IsAutomaticFanControlDisableSupported && IsSpecificFanControlSupported)
                    {
                        // Check for EC control state changes that need to be applied.
                        if (_ecFanControlRequested && !_state.EcFanControlEnabled)
                        {
                            _state.EcFanControlEnabled = true;
                            _fanController.EnableAutomaticFanControl();
                            Log.Write("Enabled EC fan control – manual mode");

                            _state.Fan1Level = null;
                            _state.Fan2Level = null;
                            _fan1LevelRequested = null;
                            _fan2LevelRequested = null;
                        }
                        else if (!_ecFanControlRequested && _state.EcFanControlEnabled)
                        {
                            _state.EcFanControlEnabled = false;
                            _fanController.DisableAutomaticFanControl();
                            Log.Write("Disabled EC fan control – manual mode");
                        }

                        // Check for fan control state changes that need to be applied.
                        if (!_state.EcFanControlEnabled)
                        {
                            if (_state.Fan1Level != _fan1LevelRequested)
                            {
                                _state.Fan1Level = _fan1LevelRequested;
                                if (_fan1LevelRequested != null)
                                {
                                    _fanController.SetFanLevel((FanLevel)_fan1LevelRequested, IsIndividualFanControlSupported ? FanIndex.Fan1 : FanIndex.AllFans);
                                }
                            }

                            if (_state.Fan2Present && IsIndividualFanControlSupported && _state.Fan2Level != _fan2LevelRequested)
                            {
                                _state.Fan2Level = _fan2LevelRequested;
                                if (_fan2LevelRequested != null)
                                {
                                    _fanController.SetFanLevel((FanLevel)_fan2LevelRequested, FanIndex.Fan2);
                                }
                            }
                        }

                        // Warn if a fan is set to completely off.
                        if (!_state.EcFanControlEnabled && (_state.Fan1Level == FanLevel.Off || (_state.Fan2Present && _state.Fan2Level == FanLevel.Off)))
                        {
                            _state.ConsistencyModeStatus = "Warning: Fans set to \"off\" will not turn on regardless of temperature or load on the system";
                        }
                        else
                        {
                            _state.ConsistencyModeStatus = " ";
                        }
                    }
                    else if (_state.OperationMode == OperationMode.Consistency && IsAutomaticFanControlDisableSupported)
                    {
                        // Consistency mode logic.
                        ConsistencyModeLogic();
                    }

                    // See if we need to update the BIOS thermal setting.
                    if (_state.ThermalSetting != ThermalSetting.Error && RequestedThermalSetting != _state.ThermalSetting)
                    {
                        DellSmbiosSmi.SetThermalSetting((ThermalSetting)RequestedThermalSetting);
                        _state.UpdateThermalSetting();
                    }

                    // Check to see if the active audio device has disappeared.
                    if (_state.AudioThreadRunning && !_state.AudioDevices.Contains(_state.SelectedAudioDevice))
                    {
                        // Remember the audio device in case it reappears.
                        _state.BringBackAudioDevice = _state.SelectedAudioDevice;

                        // Terminate the audio thread.
                        _soundPlayer?.RequestTermination();
                    }

                    _requestSemapreplaced.Release();
                    _state.Release();
                    releaseSemapreplaced = false;

                    UpdateForm();

                    Thread.Sleep(Core.RefreshInterval);
                }

                // If we got out of the loop without error, the program is terminating.
                if (IsAutomaticFanControlDisableSupported)
                {
                    _fanController.EnableAutomaticFanControl();
                    Log.Write("Enabled EC fan control – shutdown");
                }

                // Clean up as the program terminates.
                _fanController.Shutdown();
            }
            catch (Exception exception)
            {
                if (releaseSemapreplaced)
                {
                    _state.Release();
                }

                _state.WaitOne();
                _state.Error = string.Format("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
                _state.Release();

                Log.Write(_state.Error);
            }

            _state.WaitOne();
            _state.BackgroundThreadRunning = false;
            _state.Release();

            UpdateForm();
        }

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

private void RunWorkerThread(object threadIndex)
      {
        WorkerThread workerThread = workerThreads[(int)threadIndex];

        while (true)
        {
          // Wait for a task.
          workerThread.TaskWaiting.WaitOne();

          // Exit if task is empty.
          if (LoopFunction == null)
          {
            return;
          }

          bool didMoveNext;
          T localItem = default(T);
          lock (this.enumerator)
          {
            didMoveNext = enumerator.MoveNext();
            if (didMoveNext)
            {
              localItem = enumerator.Current;
            }
          }

          while (didMoveNext == true)
          {
            ////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
            LoopFunction(localItem);
            lock (this.enumerator)
            {
              didMoveNext = enumerator.MoveNext();
              if (didMoveNext)
              {
                localItem = enumerator.Current;
              }
            }
          }

          // Signal that thread is idle.
          workerThread.ThreadIdle.Set();
        }
      }

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

private void RunWorkerThread(object threadIndex) {
				WorkerThread workerThread = workerThreads[(int)threadIndex];

				while(true) {
					// Wait for a task.
					workerThread.TaskWaiting.WaitOne();

					// Exit if task is empty.
					if(LoopFunction == null) {
						return;
					}

					bool didMoveNext;
					T localItem = default(T);
					lock (this.enumerator) {
						didMoveNext = enumerator.MoveNext();
						if(didMoveNext) {
							localItem = enumerator.Current;
						}
					}

					while(didMoveNext == true) {
						////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
						LoopFunction(localItem);
						lock (this.enumerator) {
							didMoveNext = enumerator.MoveNext();
							if(didMoveNext) {
								localItem = enumerator.Current;
							}
						}
					}

					// Signal that thread is idle.
					workerThread.ThreadIdle.Set();
				}
			}

19 View Source File : WebViewRender.cs
License : MIT License
Project Creator : adamped

protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
		{
			base.OnElementChanged(e);

			var oldWebView = e.OldElement as WebViewer;
			if (oldWebView != null)
				oldWebView.EvaluateJavascript = null;

			var newWebView = e.NewElement as WebViewer;
			if (newWebView != null)
				newWebView.EvaluateJavascript = async (js) =>
				{

					ManualResetEvent reset = new ManualResetEvent(false);
					var response = "";
					Device.BeginInvokeOnMainThread(() =>
					{
						System.Diagnostics.Debug.WriteLine("Javascript Send: " + js);
						Control?.EvaluateJavascript(js, new JavascriptCallback((r) => { response = r; reset.Set(); }));
					});
					await Task.Run(() => { reset.WaitOne(); });
					if (response == "null")
						response = string.Empty;

					return response;
				};

			if (Control != null && e.NewElement != null)
			{
				InitializeCommands((WebViewer)e.NewElement);
				SetupControl();
			}
		}

19 View Source File : GrpcPeerTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public void EnqueueBlock_ShouldExecuteCallback_Test()
        {
            AutoResetEvent executed = new AutoResetEvent(false);

            NetworkException exception = null;
            bool called = false;
            _nonInterceptedPeer.EnqueueBlock(new BlockWithTransactions(), ex =>
            {
                exception = ex;
                called = true;
                executed.Set();
            });

            executed.WaitOne();
            exception.ShouldBeNull();
            called.ShouldBeTrue();
        }

19 View Source File : BTCChinaWebSocketApi.cs
License : MIT License
Project Creator : aabiryukov

public void Stop()
		{
			if (m_webSocket == null)
				return;

			//close the connection.
			m_webSocket.Send(string.Format(CultureInfo.InvariantCulture, "{0}{1}", (int)EngineioMessageType.MESSAGE, (int)SocketioMessageType.DISCONNECT));
//			Thread.Sleep(100);

			using (var timerDisposed = new ManualResetEvent(false))
			{
				m_pingIntervalTimer.Dispose(timerDisposed);
				timerDisposed.WaitOne();
				m_pingIntervalTimer = null;
			}

			using (var timerDisposed = new ManualResetEvent(false))
			{
				m_pingTimeoutTimer.Dispose(timerDisposed);
				timerDisposed.WaitOne();
				m_pingTimeoutTimer = null;
			}

			m_webSocket.Close();
			m_webSocket.Dispose();
			m_webSocket = null;
		}

19 View Source File : FortniteClient.cs
License : MIT License
Project Creator : AeonLucid

public async Task<ProfileResponse> FindPlayerAsync(Platform platform, string epicNickname)
        {
            try
            {
                _queue.WaitOne();

                if (_rateLimitRemaining == 0)
                {
                    var startTime = DateTimeOffset.UtcNow;
                    var difference = _rateLimitResetRemaining - startTime;

                    if (difference > TimeSpan.Zero)
                    {
                        await Task.Delay(difference);
                    }
                    
                    _rateLimitRemaining = RateLimitAmount;
                    _rateLimitResetRemaining = DateTimeOffset.UtcNow + RateLimitDuration;
                }

                var url = Url.Combine("profile", platform.ToString().ToLower(), epicNickname);

                return await url.WithClient(_client).GetJsonAsync<ProfileResponse>();
            }
            finally
            {
                _rateLimitRemaining--;
                _queue.Release();
            }
        }

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

public void DoForEach(IEnumerable<T> items, ForEachLoopDelegate loopBody) {
                this.enumerator = items.GetEnumerator();
                this.LoopFunction = loopBody;

                // Signal waiting task to all threads and mark them not idle.
                for (int i = 0; i < this.threadCount; i++) {
                    WorkerThread workerThread = workerThreads[i];
                    workerThread.ThreadIdle.Reset();
                    workerThread.TaskWaiting.Set();
                }

                // Wait until all threads become idle
                for (int i = 0; i < this.threadCount; i++) {
                    WorkerThread workerThread = workerThreads[i];
                    workerThread.ThreadIdle.WaitOne();
                }
            }

19 View Source File : SimpleLooper.cs
License : The Unlicense
Project Creator : aeroson

public void WaitForTaskCompletion()
        {
            if (Interlocked.Decrement(ref tasksRemaining) == 0)
            {
                allThreadsIdleNotifier.Set();
            }
            allThreadsIdleNotifier.WaitOne();

            //When it gets here, it means things are successfully idle'd.
            tasksRemaining = 1;
            allThreadsIdleNotifier.Reset();
        }

19 View Source File : UserLock.cs
License : Apache License 2.0
Project Creator : 0xFireball

public void ObtainExclusiveWrite()
        {
            // Wait for exclusive read and write
            _writeFree.WaitOne();
            _readFree.WaitOne();
        }

19 View Source File : ByteBufferTests.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

[Test]
	[Ignore("It fails, perhaps because it is run from nunit")]
	public void FileSaveTest1() {
		ByteBuffer bb = ByteBuffer.FromFile("test1.bin");
		byte[] ba = {0x41, 0x61};
		long size1 = bb.Size;

		bb.Insert(768, ba, 0, ba.LongLength);
		replacedert.AreEqual(size1 + 2, bb.Size, "#1");

		IAsyncResult ar = bb.BeginSaveAs("test2.bin", null, null);
		ar.AsyncWaitHandle.WaitOne();
		bb.CloseFile();

		ByteBuffer bb1 = ByteBuffer.FromFile("test2.bin");

		replacedert.AreEqual(bb.Size, bb1.Size, "#2");
		long size = bb1.Size;

		for (int i = 0; i < size; i++) {
			if (bb1[i] != bb[i])
				replacedert.Fail(string.Format("#3 Difference at {0} ({1}!={2})", i, bb1[i], bb[i]));
		}
	}

19 View Source File : ThreadPool.cs
License : MIT License
Project Creator : adrenak

private void SingleThreadFunc() {
            for (;;) {
                while (m_numTasks == 0) {
                    m_putNotification.WaitOne();
                }
                TaskInfo task = m_taskQueue[m_nGetPointer++];
                if (m_nGetPointer == m_taskQueue.Length) {
                    m_nGetPointer = 0;
                }
                if (Interlocked.Decrement(ref m_numTasks) == m_taskQueue.Length - 1) {
                    m_getNotification.Set();
                }
                task.callback(task.args);
            }
        }

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

public void DoFor(int start, int stop, ForLoopDelegate loopBody) {
				this.currentJobIndex = start - 1;
				this.stopIndex = stop;
				this.LoopFunction = loopBody;

				// Signal waiting task to all threads and mark them not idle.
				for(int i = 0; i < this.threadCount; i++) {
					WorkerThread workerThread = workerThreads[i];
					workerThread.ThreadIdle.Reset();
					workerThread.TaskWaiting.Set();
				}

				// Wait until all threads become idle
				for(int i = 0; i < this.threadCount; i++) {
					WorkerThread workerThread = workerThreads[i];
					workerThread.ThreadIdle.WaitOne();
				}
			}

19 View Source File : UserLock.cs
License : Apache License 2.0
Project Creator : 0xFireball

public void ObtainExclusiveRead()
        {
            _readFree.WaitOne();
        }

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

public void DoForEach(IEnumerable<T> items, ForEachLoopDelegate loopBody) {
				this.enumerator = items.GetEnumerator();
				this.LoopFunction = loopBody;

				// Signal waiting task to all threads and mark them not idle.
				for(int i = 0; i < this.threadCount; i++) {
					WorkerThread workerThread = workerThreads[i];
					workerThread.ThreadIdle.Reset();
					workerThread.TaskWaiting.Set();
				}

				// Wait until all threads become idle
				for(int i = 0; i < this.threadCount; i++) {
					WorkerThread workerThread = workerThreads[i];
					workerThread.ThreadIdle.WaitOne();
				}
			}

19 View Source File : State.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public void WaitOne()
        {
            _ = _semapreplaced.WaitOne();
            _changesAllowed = true;
        }

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

public void DoForEach(IEnumerable<T> items, ForEachLoopDelegate loopBody)
      {
        this.enumerator = items.GetEnumerator();
        this.LoopFunction = loopBody;

        // Signal waiting task to all threads and mark them not idle.
        for (int i = 0; i < this.threadCount; i++)
        {
          WorkerThread workerThread = workerThreads[i];
          workerThread.ThreadIdle.Reset();
          workerThread.TaskWaiting.Set();
        }

        // Wait until all threads become idle
        for (int i = 0; i < this.threadCount; i++)
        {
          WorkerThread workerThread = workerThreads[i];
          workerThread.ThreadIdle.WaitOne();
        }
      }

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

public void DoFor(int start, int stop, ForLoopDelegate loopBody)
      {
        this.currentJobIndex = start - 1;
        this.stopIndex = stop;
        this.LoopFunction = loopBody;

        // Signal waiting task to all threads and mark them not idle.
        for (int i = 0; i < this.threadCount; i++)
        {
          WorkerThread workerThread = workerThreads[i];
          workerThread.ThreadIdle.Reset();
          workerThread.TaskWaiting.Set();
        }

        // Wait until all threads become idle
        for (int i = 0; i < this.threadCount; i++)
        {
          WorkerThread workerThread = workerThreads[i];
          workerThread.ThreadIdle.WaitOne();
        }
      }

19 View Source File : Core.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public void RequestEcFanControl(bool enabled)
        {
            _requestSemapreplaced.WaitOne();
            _ecFanControlRequested = enabled;
            _requestSemapreplaced.Release();
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : advancedmonitoring

private void ContentUpdate(object obj)
        {
            var t = (Tuple<string, UIPerformWorkWindow>) obj;
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { EdtContent.Text = ""; }));
            var content = t.Item1.Substring(0, t.Item1.Length - 1);
            var last = t.Item1.Substring(content.Length);
            var all = content.Length + 1;
            var setted = 0;
            while (content.Length > CONTENT_CHUNK_SIZE)
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action<string>((x) => { EdtContent.AppendText(x); }), content.Substring(0, CONTENT_CHUNK_SIZE));
                content = content.Substring(CONTENT_CHUNK_SIZE);
                setted += CONTENT_CHUNK_SIZE;
                t.Item2.Percentage = (int) ((setted + 0.0) * 100 / (all + 0.0));
                if (t.Item2.AbortEvent.WaitOne(0))
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { EdtContent.TextChanged += EdtContent_OnTextChanged; }));
                    Thread.CurrentThread.Abort();
                    return;
                }
            }
            if (content.Length > 0)
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action<string>((x) => { EdtContent.AppendText(x); }), content);
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action<string>((x) => { EdtContent.TextChanged += EdtContent_OnTextChanged; EdtContent.AppendText(x); }), last);

            var wait = new ManualResetEvent(false);
            Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action<ManualResetEvent>((x) => { x.Set(); }), wait);
            wait.WaitOne();
            t.Item2.AbortEvent.Set();
            Thread.CurrentThread.Abort();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {
			if (args != null && args.Length == 0) args = new[] { "?" };

			ManualResetEvent wait = new ManualResetEvent(false);
			new Thread(() => {
				Thread.CurrentThread.Join(TimeSpan.FromMilliseconds(10));

                try
                {
                    ConsoleApp app = new ConsoleApp(args, wait);
                }
                finally
                {
                    wait.Set();
                }
			}).Start();
			wait.WaitOne();
			return;
		}

19 View Source File : KoiInfo.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static void RetrieveKoi(ConfuserContext ctx)
        {
            if(settings.NoUI)
            {
                ctx.Logger.Log("Retrieving Koi...");

                var sys = new KoiSystem();
                var hnd = new ManualResetEvent(false);
                var okay = false;
                sys.Progress += _ => { };
                sys.Finish += f =>
                {
                    okay = f;
                    hnd.Set();
                };
                sys.Login(settings.KoiID);
                hnd.WaitOne();
                if(!okay)
                    throw new InvalidOperationException("Authentication failed.");
            }
            else
            {
                Application.EnableVisualStyles();
                if(new LoginPrompt {TopLevel = true}.ShowDialog() != DialogResult.OK)
                    throw new InvalidOperationException("Authentication failed.");
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : adospace

private static void Monitor(string replacedemblyPath)
        {
            var cancellationTokenSource = new CancellationTokenSource();

            Console.WriteLine($"Start listening '{replacedemblyPath}'");

            // Create a new FileSystemWatcher and set its properties.
            using var watcher = new FileSystemWatcher
            {
                Path = Path.GetDirectoryName(replacedemblyPath),

                // Watch for changes in LastAccess and LastWrite times, and
                // the renaming of files or directories.
                NotifyFilter = NotifyFilters.LastWrite,
                                //NotifyFilters.LastAccess
                                // | NotifyFilters.LastWrite
                                // | NotifyFilters.FileName
                                // | NotifyFilters.DirectoryName,

                // Only watch text files.
                Filter = Path.GetFileName(replacedemblyPath) //"*.txt"
            };

            // Add event handlers.
            watcher.Changed += OnChanged;
            //watcher.Created += OnChanged;
            //watcher.Deleted += OnChanged;
            //watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press Cancel Key to quit");
            //while (Console.Read() != 'q') ;

            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cancellationTokenSource.Cancel();
            };

            cancellationTokenSource.Token.WaitHandle.WaitOne();

            cancellationTokenSource.Cancel();
        }

19 View Source File : GrpcPeerTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public void EnqueueTransaction_ShouldExecuteCallback_Test()
        {
            AutoResetEvent executed = new AutoResetEvent(false);

            NetworkException exception = null;
            var transaction = new Transaction();
            bool called = false;
            _nonInterceptedPeer.EnqueueTransaction(transaction, ex =>
            {
                exception = ex;
                called = true;
                executed.Set();
            });

            executed.WaitOne();
            exception.ShouldBeNull();
            called.ShouldBeTrue();
        }

19 View Source File : ResourceThrottle.cs
License : Apache License 2.0
Project Creator : 0xFireball

public void Acquire()
        {
            _throttle.WaitOne();
        }

19 View Source File : GrpcPeerTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public void EnqueueLibAnnouncement_ShouldExecuteCallback_Test()
        {
            AutoResetEvent executed = new AutoResetEvent(false);

            NetworkException exception = null;
            bool called = false;
            _nonInterceptedPeer.EnqueueLibAnnouncement(new LibAnnouncement(), ex =>
            {
                exception = ex;
                called = true;
                executed.Set();
            });

            executed.WaitOne();
            exception.ShouldBeNull();
            called.ShouldBeTrue();
        }

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

private void RunWorkerThread(object threadIndex) {
                WorkerThread workerThread = workerThreads[(int)threadIndex];
                int localJobIndex = 0;

                while (true) {
                    // Wait for a task.
                    workerThread.TaskWaiting.WaitOne();

                    // Exit if task is empty.
                    if (LoopFunction == null) {
                        return;
                    }

                    localJobIndex = Interlocked.Increment(ref currentJobIndex);

                    while (localJobIndex < stopIndex) {
                        ////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
                        LoopFunction(localJobIndex);
                        localJobIndex = Interlocked.Increment(ref currentJobIndex);
                    }

                    // Signal that thread is idle.
                    workerThread.ThreadIdle.Set();
                }
            }

19 View Source File : ParallelLoopWorker.cs
License : The Unlicense
Project Creator : aeroson

internal void Work()
        {
            if (threadStart != null)
            {
                threadStart();
            }
            threadStart = null;

            while (true)
            {
                //When the owning ParallelLooper is told to start a loop, it will notify the worker via this signal.
                getToWork.WaitOne();
                if (manager.currentLoopBody == null)
                {
                    //Woops, looks like it's time for me to die.
                    manager.OnWorkerFinish();
                    return;
                }

                while (manager.jobIndex <= manager.maxJobIndex)
                {
                    //Claim a piece of job.
                    int jobIndex = Interlocked.Increment(ref manager.jobIndex);
                    //The job interval.
                    int endIndex = jobIndex * iterationsPerSteal;
                    int beginIndex = endIndex - iterationsPerSteal;

                    //Do the job piece.  Make sure you don't do more than exists in the list itself.
                    for (int i = beginIndex; i < endIndex && i < finalIndex; i++)
                    {
                        manager.currentLoopBody(i);
                    }
                } //this is not 'thread safe' but the result of the unsafety is a quick fail in the worst case.

                manager.OnWorkerFinish();
            }
        }

19 View Source File : WebSocketApi.cs
License : MIT License
Project Creator : aabiryukov

public void Stop()
		{
			if (m_webSocket == null)
				return;

			using (var timerDisposed = new ManualResetEvent(false))
			{
				m_pingIntervalTimer.Dispose(timerDisposed);
				timerDisposed.WaitOne();
				m_pingIntervalTimer = null;
			}

			using (var timerDisposed = new ManualResetEvent(false))
			{
				m_pingTimeoutTimer.Dispose(timerDisposed);
				timerDisposed.WaitOne();
				m_pingTimeoutTimer = null;
			}

			m_webSocket.Close();
			m_webSocket.Dispose();
			m_webSocket = null;
		}

19 View Source File : ThreadTaskManager.cs
License : The Unlicense
Project Creator : aeroson

private void ThreadExecutionLoop()
            {
                //Perform any initialization requested.
                if (threadStart != null)
                    threadStart();
                TaskEntry task;

                while (true)
                {
                    resetEvent.WaitOne();
                    while (true)
                    {
                        if (!taskData.TryDequeueFirst(out task))
                        {
                            bool gotSomething = false;
                            for (int i = 1; i < manager.workers.Count; i++)
                            {
                                if (TrySteal((index + i) % manager.workers.Count, out task))
                                {
                                    gotSomething = true;
                                    break;
                                }
                            }
                            if (!gotSomething)
                                break; //Nothing to steal and I'm broke! Guess I'll mosey on out
                        }
                        try
                        {
                            if (task.Task != null)
                                task.Task(task.Info);
                            if (Interlocked.Decrement(ref manager.tasksRemaining) == 0)
                            {
                                manager.allThreadsIdleNotifier.Set();
                            }
                            if (task.Task == null)
                                return;
                        }
                        catch (ArithmeticException arithmeticException)
                        {
                            throw new ArithmeticException(
                                "Some internal mulreplacedhreaded arithmetic has encountered an invalid state.  Check for invalid enreplacedy momentums, velocities, and positions; propagating NaN's will generally trigger this exception in the getExtremePoint function.",
                                arithmeticException);
                        }
                    }
                }
            }

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

private void RunWorkerThread(object threadIndex) {
                WorkerThread workerThread = workerThreads[(int)threadIndex];

                while (true) {
                    // Wait for a task.
                    workerThread.TaskWaiting.WaitOne();

                    // Exit if task is empty.
                    if (LoopFunction == null) {
                        return;
                    }

                    bool didMoveNext;
                    T localItem = default(T);
                    lock (this.enumerator) {
                        didMoveNext = enumerator.MoveNext();
                        if (didMoveNext) {
                            localItem = enumerator.Current;
                        }
                    }

                    while (didMoveNext == true) {
                        ////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
                        LoopFunction(localItem);
                        lock (this.enumerator) {
                            didMoveNext = enumerator.MoveNext();
                            if (didMoveNext) {
                                localItem = enumerator.Current;
                            }
                        }
                    }

                    // Signal that thread is idle.
                    workerThread.ThreadIdle.Set();
                }
            }

19 View Source File : ParallelLooper.cs
License : The Unlicense
Project Creator : aeroson

public void RemoveThread()
        {
            if (workers.Count > 0)
            {
                lock (workers[0].disposedLocker)
                {
                    if (!workers[0].disposed)
                    {
                        currentLoopBody = null;
                        workerCount = 1;
                        workers[0].getToWork.Set();
                        loopFinished.WaitOne();
                        workers[0].Dispose();
                    }
                }
                workers.RemoveAt(0);
            }
        }

19 View Source File : LogFileWriter.cs
License : MIT License
Project Creator : 0ffffffffh

public void Dispose()
        {
            lock (lck)
            {
                ManualResetEvent mre = new ManualResetEvent(false);
                flushTimer.Dispose(mre);

                mre.WaitOne();

                logFile.Dispose();
                logFile = null;
                mre.Dispose();
            }
        }

19 View Source File : SimpleLooper.cs
License : The Unlicense
Project Creator : aeroson

private void ThreadExecutionLoop()
            {
                //Perform any initialization requested.
                if (threadStart != null)
                    threadStart(initializationInformation);
                object information = null;

                while (true)
                {
                    Action<object> task = null;
                    lock (taskQueue)
                    {
                        if (taskQueue.Count > 0)
                        {
                            task = taskQueue.Dequeue();
                            if (task == null)
                            {
                                Dispose();
                                return;
                            }

                            information = taskInformationQueue.Dequeue();
                        }
                    }
                    if (task != null)
                    {
                        //Perform the task!
                        try
                        {
                            task(information);
                        }
                        catch (ArithmeticException arithmeticException)
                        {
                            throw new ArithmeticException(
                                "Some internal mulreplacedhreaded arithmetic has encountered an invalid state.  Check for invalid enreplacedy momentums, velocities, and positions; propagating NaN's will generally trigger this exception in the getExtremePoint function.",
                                arithmeticException);
                        }
                        if (Interlocked.Decrement(ref manager.tasksRemaining) == 0)
                        {
                            manager.allThreadsIdleNotifier.Set();
                            resetEvent.WaitOne();
                        }
                    }
                    else
                        resetEvent.WaitOne();
                }
            }

19 View Source File : ThreadPool.cs
License : MIT License
Project Creator : adrenak

private void ThreadFunc() {
            for (;;) {
                m_semapreplaced.WaitOne();
                int nCurrentPointer, nNextPointer;
                do {
                    nCurrentPointer = m_nGetPointer;
                    nNextPointer = nCurrentPointer + 1;
                    if (nNextPointer == m_taskQueue.Length) {
                        nNextPointer = 0;
                    }
                } while (Interlocked.CompareExchange(ref m_nGetPointer, nNextPointer, nCurrentPointer) != nCurrentPointer);
                TaskInfo task = m_taskQueue[nCurrentPointer];
                if (Interlocked.Decrement(ref m_numTasks) == m_taskQueue.Length - 1) {
                    m_getNotification.Set();
                }
                task.callback(task.args);
            }
        }

19 View Source File : Core.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public void RequestThermalSetting(ThermalSetting requestedThermalSetting)
        {
            _requestSemapreplaced.WaitOne();
            RequestedThermalSetting = requestedThermalSetting;
            _requestSemapreplaced.Release();
        }

19 View Source File : Watchdog.cs
License : MIT License
Project Creator : 0ffffffffh

public void Dispose()
        {
            if (workTimer == null)
                return;

            Log.Info("Watchdog stopping..");

            ManualResetEvent mre = new ManualResetEvent(false);
            
            workTimer.Dispose(mre);

            mre.WaitOne();

            if (this.wts.Ws != null)
                this.wts.Ws.Release();

            watchList.Clear();
            watchList = null;

            watchdogWorkerCb = null;

            mre.Dispose();

            Log.Info("Watchdog stopped");
            

        }

19 View Source File : RequestQueue.cs
License : MIT License
Project Creator : 0ffffffffh

public static ISozlukRequestHandler PickRequest()
        {
            ISozlukRequestHandler req = null;

            mre.WaitOne();

            if (cancelled)
                return null;

            lock(synchObj)
            {
                if (Requests.Count > 0)
                    req = Requests.Dequeue();

                if (Requests.Count == 0)
                {
                    mre.Reset();
                }
            }

            return req;
        }

19 View Source File : UserLock.cs
License : Apache License 2.0
Project Creator : 0xFireball

public void ObtainConcurrentRead()
        {
            // Lock writing, and allow multiple concurrent reads
            _writeFree.WaitOne();
        }

19 View Source File : Core.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public void RequestFan2Level(FanLevel? level)
        {
            _requestSemapreplaced.WaitOne();
            _fan2LevelRequested = level;
            _requestSemapreplaced.Release();
        }

19 View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak

private void RunWorkerThread(object threadIndex)
      {
        WorkerThread workerThread = workerThreads[(int)threadIndex];
        int localJobIndex = 0;

        while (true)
        {
          // Wait for a task.
          workerThread.TaskWaiting.WaitOne();

          // Exit if task is empty.
          if (LoopFunction == null)
          {
            return;
          }

          localJobIndex = Interlocked.Increment(ref currentJobIndex);

          while (localJobIndex < stopIndex)
          {
            ////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
            LoopFunction(localJobIndex);
            localJobIndex = Interlocked.Increment(ref currentJobIndex);
          }

          // Signal that thread is idle.
          workerThread.ThreadIdle.Set();
        }
      }

See More Examples