System.Threading.EventWaitHandle.Set()

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

3894 Examples 7

19 Source : GrpcPeerTests.cs
with MIT License
from 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 Source : GrpcPeerTests.cs
with MIT License
from AElfProject

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

            NetworkException exception = null;
            _nonInterceptedPeer.IsConnected = false;
            Should.Throw<NetworkException>(() =>
                _nonInterceptedPeer.EnqueueAnnouncement(new BlockAnnouncement(), ex =>
                {
                    exception = ex;
                    executed.Set();
                }));
        }

19 Source : GrpcPeerTests.cs
with MIT License
from AElfProject

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

            NetworkException exception = null;
            _nonInterceptedPeer.IsConnected = false;

            Should.Throw<NetworkException>(()=>
                _nonInterceptedPeer.EnqueueBlock(new BlockWithTransactions(), ex =>
                {
                    exception = ex;
                    executed.Set();
                }));
        }

19 Source : GrpcPeerTests.cs
with MIT License
from AElfProject

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

            NetworkException exception = null;
            _nonInterceptedPeer.IsConnected = false;

            Should.Throw<NetworkException>(()=>
                _nonInterceptedPeer.EnqueueTransaction(new Transaction(), ex =>
                {
                    exception = ex;
                    executed.Set();
                }));
        }

19 Source : GrpcPeerTests.cs
with MIT License
from AElfProject

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

            NetworkException exception = null;
            _nonInterceptedPeer.IsConnected = false;

            Should.Throw<NetworkException>(()=>
                _nonInterceptedPeer.EnqueueLibAnnouncement(new LibAnnouncement(), ex =>
                {
                    exception = ex;
                    executed.Set();
                }));
        }

19 Source : ThreadTaskManager.cs
with The Unlicense
from aeroson

internal void EnqueueTask(Action<object> task, object taskInformation)
            {
                Interlocked.Increment(ref manager.tasksRemaining);
                taskData.Enqueue(new TaskEntry(task, taskInformation));
                resetEvent.Set();
            }

19 Source : ThreadTaskManager.cs
with The Unlicense
from 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 Source : ThreadTaskManager.cs
with The Unlicense
from 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 Source : SimpleLooper.cs
with The Unlicense
from aeroson

private void ShutDownThread()
            {
                //Let the manager know that it is done with its 'task'!
                if (Interlocked.Decrement(ref manager.tasksRemaining) == 0)
                {
                    if (!manager.disposed) //Don't mess with the handle if it's already disposed.
                        manager.allThreadsIdleNotifier.Set();
                }
                //Dump out any remaining tasks in the queue.
                for (int i = 0; i < taskQueue.Count; i++) //This is still safe since shutDownThread is called from within a lock(taskQueue) block.
                {
                    taskQueue.Dequeue();
                    if (Interlocked.Decrement(ref manager.tasksRemaining) == 0)
                    {
                        if (!manager.disposed) //Don't mess with the handle if it's already disposed.
                            manager.allThreadsIdleNotifier.Set();
                    }
                }

                lock (manager.workers)
                    manager.workers.Remove(this);
            }

19 Source : SimpleLooper.cs
with The Unlicense
from 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 Source : ParallelLooper.cs
with The Unlicense
from aeroson

internal void OnWorkerFinish()
        {
            if (Interlocked.Decrement(ref workerCount) == 0)
                loopFinished.Set();
        }

19 Source : SimpleLooper.cs
with The Unlicense
from 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 Source : SimpleLooper.cs
with The Unlicense
from aeroson

internal void EnqueueTask(Action<object> task, object taskInformation)
            {
                lock (taskQueue)
                {
                    Interlocked.Increment(ref manager.tasksRemaining);
                    taskQueue.Enqueue(task);
                    taskInformationQueue.Enqueue(taskInformation);
                    resetEvent.Set();
                }
            }

19 Source : ByteBuffer.cs
with GNU General Public License v2.0
from afrantzis

void SaveInPlaceAsyncCallback(IAsyncResult ar)
	{
		lock (LockObj) {
			SaveInPlaceOperation sipo = (SaveInPlaceOperation)ar.AsyncState;
			
			if (sipo.Result == ThreadedAsyncOperation.OperationResult.Finished) { // save went ok
				LoadWithFile(sipo.SavePath);
				
				if (undoDeque.Count > 0)
					SaveCheckpoint = undoDeque.PeekFront();
				else
					SaveCheckpoint = null;
				
				changedBeyondUndo = false;
			}
			else if (sipo.Result == ThreadedAsyncOperation.OperationResult.Cancelled) { // save cancelled
				
			}
			else if (sipo.Result == ThreadedAsyncOperation.OperationResult.CaughtException) {
				
			}
			
			// re-allow buffer usage
			this.ReadAllowed = true;
			this.ModifyAllowed = true;
			this.FileOperationsAllowed = true;
			
			this.EmitEvents = true;
			fsw.EnableRaisingEvents = true;
			
			// notify the world about the changes			
			EmitPermissionsChanged();
			EmitChanged();			
			
			// if user provided a callback, call it now
			if (userSaveAsyncCallback != null)
				userSaveAsyncCallback(ar);
			
			// notify that Save has finished	
			saveFinishedEvent.Set();
		}
	}

19 Source : ByteBuffer.cs
with GNU General Public License v2.0
from afrantzis

void SaveAsyncCallback(IAsyncResult ar)
	{
		lock (LockObj) {
			SaveOperation so = (SaveOperation)ar.AsyncState;
			
			if (so.Result == SaveOperation.OperationResult.Finished) { // save went ok
				// No need to call CloseFile() MakePrivateCopyOfUndoRedo()
				// because it has already been called in SaveOperation

				LoadWithFile(so.SavePath);
				
				if (undoDeque.Count > 0)
					SaveCheckpoint = undoDeque.PeekFront();
				else
					SaveCheckpoint = null;
				
				changedBeyondUndo = false;
			}
			else if (so.Result == SaveOperation.OperationResult.Cancelled) { // save cancelled
				if (so.StageReached == SaveOperation.SaveStage.BeforeSaveAs) {
					System.IO.File.Delete(so.TempPath);
				}
				else if (so.StageReached == SaveOperation.SaveStage.BeforeDelete) {
					System.IO.File.Delete(so.TempPath);
					fileBuf.Load(so.SavePath);
				}
				else if (so.StageReached == SaveOperation.SaveStage.BeforeMove) {
					// cancel has no effect during move.
					// mark operation as successful
					so.Result = SaveOperation.OperationResult.Finished;
					LoadWithFile(so.SavePath);
				
					if (undoDeque.Count > 0)
						SaveCheckpoint = undoDeque.PeekFront();
					else
						SaveCheckpoint = null;
				}
			}
			else if (so.Result == SaveOperation.OperationResult.CaughtException) {
				if (so.StageReached == SaveOperation.SaveStage.BeforeSaveAs) {
					System.IO.File.Delete(so.TempPath);
				}
				else if (so.StageReached == SaveOperation.SaveStage.BeforeDelete) {
					System.IO.File.Delete(so.TempPath);
					fileBuf.Load(so.SavePath);
					// make sure FSW is valid (it is probably not
					// because bb.CloseFile has been called in SaveOperation)
					SetupFSW();
				}
				else if (so.StageReached == SaveOperation.SaveStage.BeforeMove) {
					// TO-DO: better handling?
					fileBuf.Load(so.SavePath);
				}
			}
			
			// re-allow buffer usage
			this.ReadAllowed = true;
			this.ModifyAllowed = true;
			this.FileOperationsAllowed = true;
			
			this.EmitEvents = true;
			fsw.EnableRaisingEvents = true;
			
			// notify the world about the changes			
			EmitPermissionsChanged();
			EmitChanged();			
			
			// if user provided a callback, call it now
			if (userSaveAsyncCallback != null)
				userSaveAsyncCallback(ar);
			
			// notify that Save has finished	
			saveFinishedEvent.Set();
		}
	}

19 Source : DataBookFinder.cs
with GNU General Public License v2.0
from afrantzis

void FindAsyncCallback(IAsyncResult ar)
	{
		GenericFindOperation state = (GenericFindOperation)ar.AsyncState;
		ThreadedAsyncOperation.OperationResult result = state.Result;
		Util.Range match = state.Match;

		DataView dv = null;

		// find DataView that owns bb
		foreach (DataViewDisplay dvtemp in dataBook.Children) {
			if (dvtemp.View.Buffer == strategy.Buffer) {
				dv = dvtemp.View;
				break;
			}
		}

		// decide what to do based on the result of the find operation
		switch (result) {
			case ThreadedAsyncOperation.OperationResult.Finished:
				if (match != null) {
					lastFound = match;
					dv.SetSelection(match.Start, match.End);//System.Console.WriteLine("Found at {0}-{1}", r.Start, r.End);
					dv.MoveCursor(match.End + 1, 0);
					dv.Display.MakeOffsetVisible(match.Start, DataViewDisplay.ShowType.Closest);
				}
				else {
					lastFound.Clear();
				}
				break;
			case ThreadedAsyncOperation.OperationResult.Cancelled:
				dv.MoveCursor(strategy.Position, 0);
				dv.Display.MakeOffsetVisible(strategy.Position, DataViewDisplay.ShowType.Closest);
				break;
			case ThreadedAsyncOperation.OperationResult.CaughtException:
				break;
			default:
				break;
		}

		inUse = false;

		// if user provided a callback, call it now
		if (userFindAsyncCallback != null)
			userFindAsyncCallback(ar);

		// notify that the find operation has finished
		findFinishedEvent.Set();
	}

19 Source : DataBookFinder.cs
with GNU General Public License v2.0
from afrantzis

IAsyncResult HandleProblematicOp(GenericFindOperation op, AsyncCallback ac)
	{
		op.Result = GenericFindOperation.OperationResult.Finished;

		findFinishedEvent.Reset();

		IAsyncResult iar = new ThreadedAsyncResult(op, findFinishedEvent, true);
		if (ac != null)
			ac(iar);

		findFinishedEvent.Set();
		return iar;
	}

19 Source : DataBookFinder.cs
with GNU General Public License v2.0
from afrantzis

void ReplaceAllAsyncCallback(IAsyncResult ar)
	{
		ReplaceAllOperation state = (ReplaceAllOperation)ar.AsyncState;
		ThreadedAsyncOperation.OperationResult result = state.Result;
		Util.Range firstMatch = state.FirstMatch;

		DataView dv = null;

		// find DataView that owns bb
		foreach (DataViewDisplay dvtemp in dataBook.Children) {
			if (dvtemp.View.Buffer == strategy.Buffer) {
				dv = dvtemp.View;
				break;
			}
		}

		// decide what to do based on the result of the Replace All operation
		if (result == ThreadedAsyncOperation.OperationResult.Cancelled) {
			dv.Buffer.Undo();
		}
		// if we have replaced at least one occurence,
		else if (result == ThreadedAsyncOperation.OperationResult.Finished && firstMatch != null) {
			lastFound = state.Match;
			// save the cursor state for undo/redo
			dv.CursorUndoDeque.AddFront(new CursorState(firstMatch.Start, 0, lastFound.Start + state.ReplacePattern.Length, 0));

			// move cursor after final replacement
			dv.SetSelection(-1, -1);
			dv.MoveCursor(lastFound.Start + state.ReplacePattern.Length, 0);
			dv.Display.MakeOffsetVisible(lastFound.Start + state.ReplacePattern.Length, DataViewDisplay.ShowType.Closest);
		}

		inUse = false;

		// if user provided a callback, call it now
		if (userFindAsyncCallback != null)
			userFindAsyncCallback(ar);

		// notify that the replace all operation has finished
		findFinishedEvent.Set();
	}

19 Source : ByteBuffer.cs
with GNU General Public License v2.0
from afrantzis

void SaveAsAsyncCallback(IAsyncResult ar)
	{
		lock (LockObj) {
			SaveAsOperation so = (SaveAsOperation)ar.AsyncState;
			
			// re-allow buffer usage
			this.FileOperationsAllowed = true;
			
			
			// make sure Save As went smoothly before doing anything
			if (so.Result==SaveAsOperation.OperationResult.Finished) {
				// make sure data in undo redo are stored safely
				// because we are going to close the file
				MakePrivateCopyOfUndoRedo();
				CloseFile();
				LoadWithFile(so.SavePath);
				
				if (undoDeque.Count > 0)
					SaveCheckpoint = undoDeque.PeekFront();
				else
					SaveCheckpoint = null;
					
				changedBeyondUndo = false;
			}
			else {
				// if cancelled or caught an exception
				// delete the file only if we have altered it
				if (so.StageReached != SaveAsOperation.Savereplacedtage.BeforeCreate) {
					try {
						System.IO.File.Delete(so.SavePath);
					}
					catch (Exception e) {
						System.Console.WriteLine(e.Message);
					}
				}
			}
			
			// re-allow buffer usage
			this.ReadAllowed = true;
			this.ModifyAllowed = true;
			
			this.EmitEvents = true;
			
			if (fsw != null)
				fsw.EnableRaisingEvents = true;
			
			// notify the world about the changes			
			EmitPermissionsChanged();
			EmitChanged();
				
			// if user provided a callback, call it now
			if (userSaveAsyncCallback != null)
				userSaveAsyncCallback(ar);
			
			// notify that Save As has finished
			saveFinishedEvent.Set();
		}
	}

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

public async Task<AuthenticationHeaderValue> GetTokenAsync()
        {
            if (_expiration > DateTime.Now)
            {
                return _accessToken;
            }

            lock(_syncObject)
            {
                _resetEvent.WaitOne();
                if (_expiration > DateTime.Now)
                {
                    return _accessToken;
                }

                _resetEvent.Reset();
            }

            try
            {
                await SetAccessTokenAsync().ConfigureAwait(true);
            }
            finally
            {
                _resetEvent.Set();
            }

            return _accessToken;                    
        }

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

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var requestUri = request.RequestUri.PathAndQuery;

                var response = base.SendAsync(request, cancellationToken);

                if (requestUri.StartsWith("/providerhub?id="))
                {
                    WaitHandle.Set();
                }

                return response;
            }

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

protected override void BeginInvokeJS(long taskId, string identifier, string argsJson)
        {
            Called.Set();
        }

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

protected override void BeginInvokeJS(long taskId, string identifier, string argsJson, JSCallResultType resultType, long targetInstanceId)
        {
            Called.Set();
        }

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

protected override void EndInvokeDotNet(DotNetInvocationInfo invocationInfo, in DotNetInvocationResult invocationResult)
        {
            Called.Set();
        }

19 Source : WaveOut.cs
with GNU General Public License v3.0
from ahmed605

public void OnCompleted()
        {
            m_PlayEvent.Set();
            m_Playing = false;
        }

19 Source : BackgroundWorkerSample.cs
with The Unlicense
from ahotko

private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Console.WriteLine($"...done, Result = {e.Result.ToString()}");
            resetEvent.Set();
        }

19 Source : ThreadSample.cs
with The Unlicense
from ahotko

public void DoWork(object instructions)
        {
            var preplacededParametersClreplaced = instructions as LaborInstructions;
            Console.WriteLine($"Doing labor... {preplacededParametersClreplaced.SomeParameter} ... and waiting to complete...");
            Thread.Sleep(1000);
            preplacededParametersClreplaced.SyncObject.Set();
        }

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

public void Execute(Task task)
        {
            // create state object
            var taskState = new StateRef<object>(new AutoResetEvent(false));

            // queue a task and wait for it to finish executing
            task.ContinueWith(TaskCompletionHandler, taskState);
            taskState.Lock.WaitOne();

            // check for and rethrow any exceptions
            if (taskState.Exception != null)
                throw taskState.Exception;

            // completion method
            void TaskCompletionHandler(Task t, object state)
            {
                // retrieve state data
                var stateRef = state as StateRef<object>;

                // retrieve any exceptions or cancellation status
                if (t.IsFaulted)
                {
                    if (t.Exception.InnerExceptions.Count == 1) // unwrap if 1
                        stateRef.Exception = t.Exception.InnerException;
                    else
                        stateRef.Exception = t.Exception;
                }
                else if (t.IsCanceled)
                {
                    stateRef.Exception = new TaskCanceledException(t);
                }

                // signal that the execution is done
                stateRef.Lock.Set();
            }
        }

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

public T Execute<T>(Task<T> task)
        {
            // create state object
            var taskState = new StateRef<T>(new AutoResetEvent(false));

            // queue a task and wait for it to finish executing
            task.ContinueWith(TaskCompletionHandler, taskState);
            taskState.Lock.WaitOne();

            // check for and rethrow any exceptions
            if (taskState.Exception != null)
                throw taskState.Exception;

            // return the result, if any
            if (taskState.HasResult)
                return taskState.Result;

            // throw exception if no result
            throw new Exception("Task returned no result.");

            // completion method
            void TaskCompletionHandler(Task<T> t, object state)
            {
                // retrieve state data
                var stateRef = state as StateRef<T>;

                // retrieve any exceptions or cancellation status
                if (t.IsFaulted)
                {
                    if (t.Exception.InnerExceptions.Count == 1) // unwrap if 1
                        stateRef.Exception = t.Exception.InnerException;
                    else
                        stateRef.Exception = t.Exception;
                }
                else if (t.IsCanceled)
                {
                    stateRef.Exception = new TaskCanceledException(t);
                }

                // return the result from the task, if any
                if (t.IsCompleted && !t.IsFaulted)
                {
                    stateRef.HasResult = true;
                    stateRef.Result = t.Result;
                }

                // signal that the execution is done
                stateRef.Lock.Set();
            }
        }

19 Source : BotHost.cs
with MIT License
from AiursoftWeb

public async Task MonitorEvents(string websocketAddress)
        {
            if (_exitEvent != null)
            {
                _botLogger.LogDanger("Bot is trying to establish a new connection while there is already a connection.");
                return;
            }
            _exitEvent = new ManualResetEvent(false);

            // Start websocket.
            var url = new Uri(websocketAddress);
            var client = new WebsocketClient(url)
            {
                ReconnectTimeout = TimeSpan.FromDays(1)
            };
            client.ReconnectionHappened.Subscribe(type => _botLogger.LogVerbose($"WebSocket: {type.Type}"));
            var subscription = client.DisconnectionHappened.Subscribe((t) =>
            {
                _botLogger.LogDanger("Websocket connection dropped!");
                _exitEvent?.Set();
                _exitEvent = null;
            });
            await client.Start();

            // log.
            _botLogger.LogInfo("Listening to your account channel.");
            _botLogger.LogVerbose(websocketAddress + "\n");
            _botLogger.AppendResult(true, 9);

            // Post connect event.
            await _eventSyncer.Init(client);
            await BuildBot.OnBotStarted();

            // Pend.
            _exitEvent?.WaitOne();
            subscription.Dispose();
            await client.Stop(WebSocketCloseStatus.NormalClosure, string.Empty);
            _botLogger.LogVerbose("Websocket connection disconnected.");
        }

19 Source : BotHost.cs
with MIT License
from AiursoftWeb

public async Task ReleaseMonitorJob()
        {
            _exitEvent?.Set();
            _exitEvent = null;
            while (!MonitorTask.IsCompleted)
            {
                await Task.Delay(200);
            }
        }

19 Source : RetryableWebSocketConnection.cs
with MIT License
from AiursoftWeb

public override Task Disconnect()
        {
            _exitEvent.Set();
            return base.Disconnect();
        }

19 Source : EventLogReader.cs
with MIT License
from akpaevj

private void LgpFilesWatcher_Event(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Changed)
                _lgpChangedCreated.Set();
        }

19 Source : AssetTreeModel.cs
with MIT License
from akof1314

public void ThreadPoolCallback(System.Object threadContext)
            {
                try
                {
                    string text = File.ReadAllText(m_Path);

                    // 搜索
                    if (string.IsNullOrEmpty(m_ReplaceStr))
                    {
                        for (int i = 0; i < m_Patterns.Count; i++)
                        {
                            if (text.Contains(m_Patterns[i]))
                            {
                                m_SearchRet[i] = true;
                            }
                        }
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder(text, text.Length * 2);
                        foreach (var pattern in m_Patterns)
                        {
                            sb.Replace(pattern, m_ReplaceStr);
                        }

                        string text2 = sb.ToString();
                        if (!string.Equals(text, text2))
                        {
                            File.WriteAllText(m_Path, text2);
                        }
                    }
                }
                catch (Exception ex)
                {
                    exception = m_Path + "\n" + ex.Message;
                }

                doneEvent.Set();
            }

19 Source : Auth.cs
with MIT License
from AL3X1

private async void AuthCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            if (sender.Uuid == AUTH_CHARACTERISTIC)
            {
                List<byte> request = args.CharacteristicValue.ToArray().ToList();
                byte authResponse = 0x10;
                byte authSendKey = 0x01;
                byte authRequestRandomAuthNumber = 0x02;
                byte authRequestEncryptedKey = 0x03;
                byte authSuccess = 0x01;
                byte authFail = 0x04;

                if (request[2] == authFail)
                    Debug.WriteLine("Authentication error");

                if (request[0] == authResponse && request[1] == authSendKey && request[2] == authSuccess)
                {
                    Debug.WriteLine("Level 2 started");

                    if (await SendAuthNumberAsync())
                        Debug.WriteLine("Level 2 success");
                }
                else if (request[0] == authResponse && request[1] == authRequestRandomAuthNumber && request[2] == authSuccess)
                {
                    Debug.WriteLine("Level 3 started");

                    if (await SendEncryptedRandomKeyAsync(args))
                        Debug.WriteLine("Level 3 success");
                }
                else if (request[0] == authResponse && request[1] == authRequestEncryptedKey && request[2] == authSuccess)
                {
                    Debug.WriteLine("Authentication completed");
                    _LocalSettings.Values["isAuthorized"] = true;
                }

                _WaitHandle.Set();
            }
        }

19 Source : HeartRate.cs
with MIT License
from AL3X1

private void HeartRateMeasurementCharacteristicValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            Debug.WriteLine("Getting HeartRate");
            if (sender.Uuid.ToString() == HEART_RATE_MEASUREMENT_CHARACTERISTIC.ToString())
                lastHeartRate = args.CharacteristicValue.ToArray()[1];

            System.Diagnostics.Debug.WriteLine($"HeartRate is {lastHeartRate} bpm");
            _WaitHandle.Set();
        }

19 Source : Identity.cs
with MIT License
from AL3X1

private async void AuthCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            if (sender.Uuid == AUTH_CHARACTERISTIC)
            {
                List<byte> request = args.CharacteristicValue.ToArray().ToList();
                byte authResponse = 0x10;
                byte authSendKey = 0x01;
                byte authRequestRandomAuthNumber = 0x02;
                byte authRequestEncryptedKey = 0x03;
                byte authSuccess = 0x01;
                byte authFail = 0x04;

                if (request[2] == authFail)
                {
                    Debug.WriteLine("Authentication error");
                    _WaitHandle.Set();
                }

                if (request[0] == authResponse && request[1] == authSendKey && request[2] == authSuccess)
                {
                    Debug.WriteLine("Level 2 started");

                    if (await SendAuthNumberAsync())
                        Debug.WriteLine("Level 2 success");
                }
                else if (request[0] == authResponse && request[1] == authRequestRandomAuthNumber && request[2] == authSuccess)
                {
                    Debug.WriteLine("Level 3 started");

                    if (await SendEncryptedRandomKeyAsync(args))
                        Debug.WriteLine("Level 3 success");
                }
                else if (request[0] == authResponse && request[1] == authRequestEncryptedKey && request[2] == authSuccess)
                {
                    Debug.WriteLine("Authentication completed");
                    _LocalSettings.Values["isAuthorized"] = true;
                    _WaitHandle.Set();
                }
            }
        }

19 Source : SampleMultiThreading.cs
with MIT License
from Alan-FGR

void stepPhysics()
    {
        //// Start simulation
        //gScene->simulate(1.0f/60.0f);
        gScene.simulate(1/60f);

        //// Start ray-cast threads
        //gRaysAvailable = gRayCount;
        //gRaysCompleted = 0;
        gRaysAvailable = gRayCount;
        gRaysCompleted = 0;

        //// Signal to each raycast thread that they can start performing raycasts.
        //for (PxU32 i=0; i < gNumThreads; ++i)
        for (uint i=0; i < gNumThreads; ++i)
        {
            //SnippetUtils::syncSet(gThreads[i].mWorkReadySyncHandle);
            gThreads[i].mWorkReadySyncHandle.Set();
        }
        
        //// Wait for raycast threads to finish.
        //SnippetUtils::syncWait(gWorkDoneSyncHandle);
        //SnippetUtils::syncReset(gWorkDoneSyncHandle);
        gWorkDoneSyncHandle.WaitOne();
        gWorkDoneSyncHandle.Reset();

        //// Fetch simulation results
        //gScene->fetchResults(true);
        gScene.fetchResults(true);
    }

19 Source : SampleMultiThreading.cs
with MIT License
from Alan-FGR

void cleanupPhysics()
    {
        //// Signal threads to quit.
        //for (PxU32 i=0; i < gNumThreads; ++i)
        for (uint i=0; i < gNumThreads; ++i)
        {
            //SnippetUtils::threadSignalQuit(gThreads[i].mThreadHandle);
            //SnippetUtils::syncSet(gThreads[i].mWorkReadySyncHandle);
            gThreads[i].quit = true;
            gThreads[i].mWorkReadySyncHandle.Set();
        }

        //// Clean up raycast threads and syncs.
        //for (PxU32 i=0; i < gNumThreads; ++i)
        for (uint i=0; i < gNumThreads; ++i)
        {
            //SnippetUtils::threadWaitForQuit(gThreads[i].mThreadHandle);
            //SnippetUtils::threadRelease(gThreads[i].mThreadHandle);
            //SnippetUtils::syncRelease(gThreads[i].mWorkReadySyncHandle);
            gThreads[i].mThreadHandle.Join();
            gThreads[i].mWorkReadySyncHandle.Close();
        }

        //// Clean up the sync for the main thread.
        //SnippetUtils::syncRelease(gWorkDoneSyncHandle);
        gWorkDoneSyncHandle.Close();

        //PX_RELEASE(gScene);
        //PX_RELEASE(gDispatcher);
        //PX_RELEASE(gPhysics);
        //PX_RELEASE(gFoundation);
        gScene.release();
        gDispatcher.release();
        gPhysics.release();
        gFoundation.release();

        //printf("SnippetMulreplacedhreading done.\n");
        System.Console.WriteLine("SnippetMulreplacedhreading done.");
    }

19 Source : SampleMultiThreading.cs
with MIT License
from Alan-FGR

static unsafe void threadExecute(object data)
    {
        //RaycastThread* raycastThread = static_cast<RaycastThread*>(data);
        RaycastThread raycastThread = (RaycastThread)data;

        //// Perform random raycasts against the scene until stop.
        //for(;;)
        for (;;)
        {
            //// Wait here for the sync to be set then reset the sync
            //// to ensure that we only perform raycast work after the 
            //// sync has been set again.
            //SnippetUtils::syncWait(raycastThread->mWorkReadySyncHandle);
            //SnippetUtils::syncReset(raycastThread->mWorkReadySyncHandle);
            raycastThread.mWorkReadySyncHandle.WaitOne();
            raycastThread.mWorkReadySyncHandle.Reset();

            //// If the thread has been signaled to quit then exit this function.
            //if (SnippetUtils::threadQuitIsSignalled(raycastThread->mThreadHandle))
            //    break;
            if (raycastThread.quit)
                break;

            //// Perform a fixed number of random raycasts against the scene
            //// and share the work between multiple threads.
            //while (SnippetUtils::atomicDecrement(&gRaysAvailable) >= 0)
            while (Interlocked.Decrement(ref gRaysAvailable) >= 0)
            {
                //PxVec3 dir = randVec3();
                PxVec3 dir = randVec3();

                //PxRaycastBuffer buf;
                //gScene->raycast(PxVec3(0.0f), dir.getNormalized(), 1000.0f, buf, PxHitFlag::eDEFAULT);
                PxRaycastBufferPtr buf = PxRaycastBufferPtr.New();
                gScene.raycast(new PxVec3(0.0f), dir.getNormalized(), 1000f, buf, PxHitFlags.eDEFAULT);

                if (render_)
                {
                    var rayNor = dir.getNormalized() * 1000;
                    DebugRenderer.Current.AddLine(new Vector3(0), new Vector3(rayNor.x, rayNor.y, rayNor.z), 0xff00ffff);
                }

                buf.Free();

                //// If this is the last raycast then signal this to the main thread.
                //if (SnippetUtils::atomicIncrement(&gRaysCompleted) == gRayCount)
                if (Interlocked.Increment(ref gRaysCompleted) == gRayCount)
                {
                //	SnippetUtils::syncSet(gWorkDoneSyncHandle);
                    gWorkDoneSyncHandle.Set();
                }
            }
        }

        //// Quit the current thread.
        //SnippetUtils::threadQuit(raycastThread->mThreadHandle);
    }

19 Source : FileSource.cs
with MIT License
from alen-smajic

public void WaitForAllRequests()
		{
			int waitTimeMs = 200;
			while (_requests.Count > 0)
			{
				lock (_lock)
				{
					List<IAsyncRequest> reqs = _requests.Keys.ToList();
					for (int i = reqs.Count - 1; i > -1; i--)
					{
						if (reqs[i].IsCompleted)
						{
							// another place to watch out if request has been cancelled
							try
							{
								_requests.Remove(reqs[i]);
							}
							catch (Exception ex)
							{
								System.Diagnostics.Debug.WriteLine(ex);
							}
						}
					}
				}

#if WINDOWS_UWP
				System.Threading.Tasks.Task.Delay(waitTimeMs).Wait();
#else
				//Thread.Sleep(50);
				// TODO: get rid of DoEvents!!! and find non-blocking wait that works for Net3.5
				//System.Windows.Forms.Application.DoEvents();

				var resetEvent = new ManualResetEvent(false);
				ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
				{
					Thread.Sleep(waitTimeMs);
					resetEvent.Set();
				}), null);
				UnityEngine.Debug.Log("before waitOne " + DateTime.Now.Ticks);
				resetEvent.WaitOne();
				UnityEngine.Debug.Log("after waitOne " + DateTime.Now.Ticks);
				resetEvent.Close();
				resetEvent = null;
#endif
			}
		}

19 Source : SuperIndexer.cs
with GNU General Public License v3.0
from alexdillon

public void BeginAsyncTransaction(IEnumerable<IMessageContainer> groupsAndChats = null)
        {
            this.OutdatedGroupIdList = new List<string>();
            this.WaitingOnGroupAndChatListings.Reset();

            if (groupsAndChats != null)
            {
                Debug.WriteLine("Updated ChatsList in BeginAsyncTransaction()");
                this.GroupsAndChats = groupsAndChats;
                this.WaitingOnGroupAndChatListings.Set();
            }
        }

19 Source : TileMapAnnotation.cs
with MIT License
from AlexGyver

private OxyImage Download(string uri)
        {
            OxyImage img = null;
            var mre = new ManualResetEvent(false);
            var request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "GET";
            request.BeginGetResponse(
               r =>
               {
                   try
                   {
                       if (request.HaveResponse)
                       {
                           var response = request.EndGetResponse(r);
                           var stream = response.GetResponseStream();

                           var ms = new MemoryStream();
                           stream.CopyTo(ms);
                           var buffer = ms.ToArray();

                           img = new OxyImage(buffer);
                           this.images[uri] = img;
                       }

                   }
                   catch (Exception e)
                   {
                       var ie = e;
                       while (ie != null)
                       {
                           System.Diagnostics.Debug.WriteLine(ie.Message);
                           ie = ie.InnerException;
                       }
                   }
                   finally
                   {
                       mre.Set();                       
                   }
               },
               request);

            mre.WaitOne();
            return img;
        }

19 Source : DnsAsyncState.cs
with Apache License 2.0
from alexreinert

internal void SetCompleted()
		{
			QueryData = null;

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


			IsCompleted = true;
			if (_waitHandle != null)
				_waitHandle.Set();

			if (UserCallback != null)
				UserCallback(this);
		}

19 Source : DnsClientAsyncState.cs
with Apache License 2.0
from alexreinert

internal void SetCompleted()
		{
			QueryData = null;

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

			IsCompleted = true;
			if (_waitHandle != null)
				_waitHandle.Set();

			if (UserCallback != null)
				UserCallback(this);
		}

19 Source : DnsClientParallelAsyncState.cs
with Apache License 2.0
from alexreinert

internal void SetCompleted()
		{
			IsCompleted = true;

			if (_waitHandle != null)
				_waitHandle.Set();

			if (UserCallback != null)
				UserCallback(this);
		}

19 Source : SampleLauncher.cs
with MIT License
from AliakseiFutryn

static void CheckSingletonInMulreplacedhreadingMode()
		{
			Thread[] threads = new Thread[ThreadsCount];
			Meeting[] meetings = new Meeting[ThreadsCount];
			EventWaitHandle threadsFinishedEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
			using (Barrier startBarrier = new Barrier(ThreadsCount), finishBarrier = new Barrier(ThreadsCount, barrier => threadsFinishedEvent.Set()))
			{
				for (int index = 0; index < ThreadsCount; index++)
				{
					threads[index] = new Thread(threadIndex =>
					{
						// Synchronizes all threads before start.
						startBarrier.SignalAndWait();
						try
						{
							int currentIndex = (int)threadIndex;
							meetings[currentIndex] = currentIndex >= ThreadsCount / 2 ? DoubleCheckedSingleton<Meeting>.Instance : LazySingleton<Meeting>.Instance;
						}
						catch (Exception ex)
						{
							Console.WriteLine(ex.Message);
						}
						finally
						{
							// Synhronizes all threads before finish.
							finishBarrier.SignalAndWait();
						}
					});
					threads[index].Start(index);
				}

				threadsFinishedEvent.WaitOne();
				Meeting lazySingletonInstance = LazySingleton<Meeting>.Instance;
				Meeting doubleCheckedSingletonInstance = DoubleCheckedSingleton<Meeting>.Instance;

				// There is an operation which is responsible for increasing some value of nearly
				// created instances and then it should be compared with all other instances which
				// were created in different threads.
				lazySingletonInstance.ParticipantsCount++;
				doubleCheckedSingletonInstance.ParticipantsCount++;

				Console.WriteLine("The participants count are equal in both instances of singleton: {0}", meetings.Take(ThreadsCount / 2).All(m => m.ParticipantsCount == lazySingletonInstance.ParticipantsCount));
				Console.WriteLine("The participants count are equal in both instances of singleton: {0}", meetings.Skip(ThreadsCount / 2).All(m => m.ParticipantsCount == lazySingletonInstance.ParticipantsCount));
			}
		}

19 Source : RuntimeAsyncResult.cs
with MIT License
from aliyunmq

internal void SignalWaitHandle()
        {
            this.IsCompleted = true;
            if (this._waitHandle != null)
            {
                this._waitHandle.Set();
            }
        }

19 Source : SasTokenProviderTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public async Task GetSasToken_Mulreplacedhread()
        {
            // Arrange
            string org_ttd = "ttd";
            string uri_ttd = string.Format(KeyVaultURI, org_ttd);

            string storageAccount_ttd = string.Format(StorageAccount, org_ttd);
            string sasDefinition_ttd = string.Format(SasDefinition, org_ttd);
            string secretName_ttd = $"{storageAccount_ttd}-{sasDefinition_ttd}";

            string org_brg = "brg";
            string uri_brg = string.Format(KeyVaultURI, org_brg);

            string storageAccount_brg = string.Format(StorageAccount, org_brg);
            string sasDefinition_brg = string.Format(SasDefinition, org_brg);
            string secretName_brg = $"{storageAccount_brg}-{sasDefinition_brg}";

            Mock<IKeyVaultClientWrapper> keyVaultClient = new Mock<IKeyVaultClientWrapper>();
            keyVaultClient.Setup(s => s.GetSecretAsync(It.IsAny<string>(), It.Is<string>(i => i == secretName_ttd))).ReturnsAsync("ttdsecret");
            keyVaultClient.Setup(s => s.GetSecretAsync(It.IsAny<string>(), It.Is<string>(i => i == secretName_brg))).ReturnsAsync("brgsecret");

            SasTokenProvider target = new SasTokenProvider(keyVaultClient.Object, _storageConfiguration.Object, _mockLogger.Object);

            // Act
            ManualResetEvent mre = new ManualResetEvent(false);
            List<Task> tasks = new List<Task>();
            for (int i = 0; i < 5; i++)
            {
                Task task1 = Task.Run(async () =>
                {
                    mre.WaitOne();
                    await target.GetSasToken(org_ttd);
                });

                tasks.Add(task1);

                Task task2 = Task.Run(async () =>
                {
                    mre.WaitOne();
                    await target.GetSasToken(org_brg);
                });

                tasks.Add(task2);
            }

            // Run all tasks.
            mre.Set();
            await Task.WhenAll(tasks);

            string ttdSecret = await target.GetSasToken(org_ttd);
            string brgSecret = await target.GetSasToken(org_brg);

            // replacedert
            replacedert.Equal("ttdsecret", ttdSecret);
            replacedert.Equal("brgsecret", brgSecret);

            keyVaultClient.Verify(s => s.GetSecretAsync(It.Is<string>(u => u == uri_ttd), It.Is<string>(i => i == secretName_ttd)), Times.Once);
            keyVaultClient.Verify(s => s.GetSecretAsync(It.Is<string>(u => u == uri_brg), It.Is<string>(i => i == secretName_brg)), Times.Once);
        }

19 Source : VideoAnalyzer.cs
with MIT License
from AlturosDestinations

private async Task<replacedyzeResult> GetVideoInfoAsync(MediaInput mediaInput, CancellationToken cancellationToken = default)
        {
            if (!File.Exists(this._ffprobePath))
            {
                return new replacedyzeResult { Successful = false, ErrorMessage = $"ffprobe could not be found {this._ffprobePath}" };
            }

            var startInfo = new ProcessStartInfo
            {
                FileName = this._ffprobePath,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
            };

            if (mediaInput.FileContent != null)
            {
                startInfo.RedirectStandardInput = true;
                startInfo.Arguments = $"-v quiet -print_format json -show_format -show_streams -";
            }
            else
            {
                startInfo.Arguments = $"-v quiet -print_format json -show_format -show_streams \"{mediaInput.FilePath}\"";
            }

            using (var outputWaitHandle = new AutoResetEvent(false))
            {
                var json = new StringBuilder();

                var dataReceived = new DataReceivedEventHandler((sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                        return;
                    }

                    json.AppendLine(e.Data);
                });

                this._process = new Process();

                try
                {
                    this._process.StartInfo = startInfo;
                    this._process.OutputDataReceived += dataReceived;

                    if (!this._process.Start())
                    {
                        return new replacedyzeResult { ErrorMessage = "Cannot start ffprobe" };
                    }

                    this._process.BeginOutputReadLine();

                    if (mediaInput.FileContent != null)
                    {
                        using (var ffprobeIn = this._process.StandardInput.BaseStream)
                        {
                            var packageSize = 100000;
                            for (var i = 0; i < mediaInput.FileContent.Length; i += packageSize)
                            {
                                var package = mediaInput.FileContent.Skip(i).Take(packageSize).ToArray();
                                await ffprobeIn.WriteAsync(package, 0, package.Length, cancellationToken);
                            }
                            await ffprobeIn.FlushAsync(cancellationToken);
                            ffprobeIn.Close();
                        }
                    }

                    if (!this._process.WaitForExit(this._timeout) || !outputWaitHandle.WaitOne(this._timeout))
                    {
                        return new replacedyzeResult { ErrorMessage = $"Timeout reached {this._timeout} (ms)" };
                    }

                    var videoInfo = JsonConvert.DeserializeObject<VideoInfoResult>(json.ToString(), this._jsonSerializerSettings);
                    if (videoInfo.Format == null && videoInfo.Streams == null)
                    {
                        return new replacedyzeResult { Successful = false, ErrorMessage = "No feedback from ffprobe" };
                    }

                    return new replacedyzeResult { Successful = true, VideoInfo = videoInfo };
                }
                catch (IOException)
                {
                    var videoInfo = JsonConvert.DeserializeObject<VideoInfoResult>(json.ToString(), this._jsonSerializerSettings);
                    if (videoInfo.Format == null && videoInfo.Streams == null)
                    {
                        return new replacedyzeResult { Successful = false, ErrorMessage = "No feedback from ffprobe (IOException)" };
                    }

                    return new replacedyzeResult { Successful = true, VideoInfo = videoInfo };
                }
                catch (Exception exception)
                {
                    return new replacedyzeResult { Successful = false, ErrorMessage = exception.ToString() };
                }
                finally
                {
                    this._process.OutputDataReceived -= dataReceived;
                    this._process?.Dispose();
                }
            }
        }

See More Examples