System.Threading.EventWaitHandle.Reset()

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

706 Examples 7

19 View Source File : GarbageCollection.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

public void WaitForThreadToStop()
        {
            m_EventThreadEnded.WaitOne();
            m_EventThreadEnded.Reset();
        }

19 View Source File : BitPickerWorker.cs
License : MIT License
Project Creator : bitcake

public bool GetMatchesPartialSync( List<BitPickerHelper.Result> results )
		{
			if( !hasWorkLeft )
				return false;

			pendingWorkerCount = workers.Length;
			allWorkersFinishedSync.Reset();

			foreach( var worker in workers )
			{
				ThreadPool.QueueUserWorkItem(
					w => ( w as BitPickerWorker ).GetMatchesPartial(),
					worker
				);
			}

			allWorkersFinishedSync.WaitOne();

			hasWorkLeft = false;
			foreach( var worker in workers )
			{
				results.AddRange( worker.results );
				worker.EnsureMatchCapacity();

				if( worker.IsIncomplete() )
					hasWorkLeft = true;
			}

			return true;
		}

19 View Source File : OAuthTokenManager.cs
License : Apache License 2.0
Project Creator : 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 View Source File : Simulator.cs
License : Apache License 2.0
Project Creator : AnotherEnd15

public float doStep()
        {
            updateDeleteAgent();

            if (workers == null)
            {
                workers = new Worker[numWorkers];
                doneEvents = new ManualResetEvent[workers.Length];
                workerAgentCount = getNumAgents();

                for (int block = 0; block < workers.Length; ++block)
                {
                    doneEvents[block] = new ManualResetEvent(false);
                    workers[block] = new Worker(block * getNumAgents() / workers.Length, (block + 1) * getNumAgents() / workers.Length, doneEvents[block]);
                }
            }

            if (workerAgentCount != getNumAgents())
            {
                workerAgentCount = getNumAgents();
                for (int block = 0; block < workers.Length; ++block)
                {
                    workers[block].config(block * getNumAgents() / workers.Length, (block + 1) * getNumAgents() / workers.Length);
                }
            }

            kdTree.buildAgentTree();

            if (workers.Length <= 1)
            {
                workers[0].step(null);
                workers[0].update(null);
            }
            else
            {

                for (int block = 0; block < workers.Length; ++block)
                {
                    doneEvents[block].Reset();
                    ThreadPool.QueueUserWorkItem(workers[block].step);
                }
                WaitHandle.WaitAll(doneEvents);

                for (int block = 0; block < workers.Length; ++block)
                {
                    doneEvents[block].Reset();
                    ThreadPool.QueueUserWorkItem(workers[block].update);
                }

                WaitHandle.WaitAll(doneEvents);
            }

          

            globalTime += timeStep;

            return globalTime;
        }

19 View Source File : SampleMultiThreading.cs
License : MIT License
Project Creator : 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 View Source File : ByteBuffer.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

public IAsyncResult BeginSaveAs(string filename, ProgressCallback progressCallback, AsyncCallback ac)
	{
		lock (LockObj) {
			if (!fileOperationsAllowed) return null;
			
			saveFinishedEvent.Reset();
			userSaveAsyncCallback = ac;
			
			SaveAsOperation so = new SaveAsOperation(this, filename, progressCallback, SaveAsAsyncCallback, useGLibIdle);
			
			// don't allow messing up with the buffer
			// while we are saving
			// ...ReadAllowed is set in SaveOperation
			// this.ReadAllowed = false;
			this.ModifyAllowed = false;
			this.FileOperationsAllowed = false;
			this.EmitEvents = false;
			if (fsw != null)
				fsw.EnableRaisingEvents = false;
			
			// start save thread
			Thread saveThread = new Thread(so.OperationThread);
			saveThread.IsBackground = true;
			saveThread.Start();
			
			return new ThreadedAsyncResult(so, saveFinishedEvent, false);
		}
		
	}

19 View Source File : BufferTest.cs
License : Apache License 2.0
Project Creator : awslabs

[Fact]
        [Trait("Category", "Integration")]
        public void TestBuffer()
        {
            ManualResetEvent sinkWaitHandle = new ManualResetEvent(false);
            Buffer<int> buffer = new Buffer<int>(10, null, l =>
            {
                sinkWaitHandle.WaitOne();
            });
            for (int i = 0; i < 5; i++)
            {
                TestBufferInternal(i, sinkWaitHandle, buffer);
                sinkWaitHandle.Reset();
            }
        }

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 : AudioPlayer.cs
License : MIT License
Project Creator : BleuBleu

protected void ResetThreadingObjects()
        {
            stopEvent.Reset();
            bufferSemapreplaced = new Semapreplaced(numBufferedFrames, numBufferedFrames);
        }

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

public static void TextChangedContentEdit()
        {
            if (_textChangedThread != null && _textChangedThread.IsAlive)
            {
                TextChangedEvent.Set();
                _textChangedThread.Join();
            }
            TextChangedEvent.Reset();
            _textChangedThread = new Thread(TextChangedFunc);
            _textChangedThread.Start(MW.GetContent());
            _textChangedSpinnerThread = new Thread(TextChangedSpinnerFunc);
            _textChangedSpinnerThread.Start();
        }

19 View Source File : PagingManager.cs
License : MIT License
Project Creator : Analogy-LogViewer

private void AddExtraColumnsIfNeeded(DataTable table, replacedogyLogMessage message)
        {
            if (message.AdditionalInformation != null && message.AdditionalInformation.Any() && Settings.CheckAdditionalInformation)
            {
                foreach (KeyValuePair<string, string> info in message.AdditionalInformation)
                {

                    if (!table.Columns.Contains(info.Key))
                    {
                        if (!owner.InvokeRequired)
                        {
                            try
                            {
                                columnsLockSlim.EnterWriteLock();
                                if (!table.Columns.Contains(info.Key))
                                {
                                    table.Columns.Add(info.Key);
                                }
                            }
                            finally
                            {
                                columnsLockSlim.ExitWriteLock();
                            }



                        }
                        else
                        {
                            owner.BeginInvoke(new MethodInvoker(() =>
                            {
                                try
                                {

                                    columnsLockSlim.EnterWriteLock();
                                    if (!table.Columns.Contains(info.Key))
                                    {
                                        columnsLockSlim.EnterWriteLock();
                                        if (!table.Columns.Contains(info.Key))
                                        {
                                            table.Columns.Add(info.Key);
                                            columnAdderSync.Set();
                                        }

                                    }
                                }
                                finally
                                {
                                    columnsLockSlim.ExitWriteLock();
                                }
                            }));
                            columnAdderSync.WaitOne();
                            columnAdderSync.Reset();
                        }
                    }
                }
            }
        }

19 View Source File : SuperIndexer.cs
License : GNU General Public License v3.0
Project Creator : 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 View Source File : DataBookFinder.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

public IAsyncResult FindPrevious(AsyncCallback ac)
	{
		if (dataBook.NPages == 0 || inUse) {
			FindPreviousOperation op = new FindPreviousOperation(strategy, null, FindAsyncCallback);
			return HandleProblematicOp(op, ac);
		}

		inUse = true;

		userFindAsyncCallback = ac;
		findFinishedEvent.Reset();

		// if this is the first time we are checking
		// for a valid pattern, emit the event
		if (firstTime == true && strategy.Pattern.Length > 0) {
			firstTime = false;
			if (FirstFind != null)
				FirstFind();
		} // is pattern acceptable?
		else if (strategy.Pattern.Length == 0)
			return null;

		DataView dv = ((DataViewDisplay)dataBook.CurrentPageWidget).View;

		strategy.Buffer = dv.Buffer;

		// decide where to start searching from
		if (!dv.Selection.IsEmpty())
			strategy.Position = dv.Selection.End;
		else
			strategy.Position = dv.CursorOffset;

		SetUpFindProgressReport();

		FindPreviousOperation fpo = new FindPreviousOperation(strategy, progressCallback, FindAsyncCallback);

		// lock the buffer, so user can't modify it while
		// searching
		strategy.Buffer.ModifyAllowed = false;
		strategy.Buffer.FileOperationsAllowed = false;

		// start find thread
		Thread findThread = new Thread(fpo.OperationThread);
		findThread.IsBackground = true;
		findThread.Start();

		return new ThreadedAsyncResult(fpo, findFinishedEvent, false);
	}

19 View Source File : ImageFormats.cs
License : GNU General Public License v3.0
Project Creator : arklumpus

internal unsafe static IntPtr FilterImageData(byte* image, int width, int height, int pixelSize, FilterModes filter, int threadCount)
        {
            threadCount = Math.Min(threadCount, height);

            IntPtr filteredMemory = Marshal.AllocHGlobal(height * (1 + width * pixelSize));

            int stride = width * pixelSize;

            byte* filteredPointer = (byte*)filteredMemory;

            IntPtr[] tempBuffers = new IntPtr[threadCount];

            Thread[] threads = new Thread[threadCount];
            int[] rowsByThread = new int[threadCount];
            EventWaitHandle[] signalsFromThreads = new EventWaitHandle[threadCount];
            EventWaitHandle[] signalsToThreads = new EventWaitHandle[threadCount];

            int firstNeededRow = threadCount;

            for (int i = 0; i < threadCount; i++)
            {
                rowsByThread[i] = i;
                signalsFromThreads[i] = new EventWaitHandle(false, EventResetMode.ManualReset);
                signalsToThreads[i] = new EventWaitHandle(false, EventResetMode.ManualReset);

                if (filter == FilterModes.Adaptive)
                {
                    tempBuffers[i] = Marshal.AllocHGlobal(5 * width * pixelSize);
                }
                else
                {
                    tempBuffers[i] = IntPtr.Zero;
                }

                byte* tempPointer = (byte*)tempBuffers[i];

                int threadIndex = i;

                threads[i] = new Thread(() =>
                {
                    while (rowsByThread[threadIndex] >= 0)
                    {
                        FilterRow(image, width, pixelSize, stride, rowsByThread[threadIndex], filter, filteredPointer, tempPointer);
                        EventWaitHandle.SignalAndWait(signalsFromThreads[threadIndex], signalsToThreads[threadIndex]);
                        signalsToThreads[threadIndex].Reset();
                    }
                });
            }

            int finished = 0;

            for (int i = 0; i < threadCount; i++)
            {
                threads[i].Start();
            }

            while (finished < threadCount)
            {
                int threadInd = EventWaitHandle.WaitAny(signalsFromThreads);

                signalsFromThreads[threadInd].Reset();

                if (firstNeededRow < height)
                {
                    rowsByThread[threadInd] = firstNeededRow;
                    firstNeededRow++;
                    signalsToThreads[threadInd].Set();
                }
                else
                {
                    rowsByThread[threadInd] = -1;
                    signalsToThreads[threadInd].Set();
                    finished++;
                }
            }

            for (int i = 0; i < threadCount; i++)
            {
                if (filter == FilterModes.Adaptive)
                {
                    Marshal.FreeHGlobal(tempBuffers[i]);
                }
            }

            return filteredMemory;
        }

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 : FormBackground.cs
License : MIT License
Project Creator : AutoItConsulting

private void TimerHandleOptionsChangeEvent()
        {
            // Lock so no chance of receiving another new options file during processing
            lock (_namedPiperServerThreadLock)
            {
                if (_eventNewOptionsAvailable.WaitOne(0))
                {
                    _eventNewOptionsAvailable.Reset();

                    // Save data
                    _osdBackgroundDir = _namedPipeXmlPayload.OsdBackgroundDir;
                    _options = _namedPipeXmlPayload.Options;

                    // Change fields based on updated options data
                    OptionsXmlOptionsObjectToFields(_options);

                    // Change the working dir to match the last AutoIt.OSDBackground.exe that was run
                    Directory.SetCurrentDirectory(_namedPipeXmlPayload.OsdBackgroundWorkingDir);

                    // Redraw the background and progress bar (size and/or color might have new options)
                    RefreshBackgroundImage(true);
                    ProgressBarRedraw();
                }
            }
        }

19 View Source File : DataBookFinder.cs
License : GNU General Public License v2.0
Project Creator : 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 View Source File : Worker.cs
License : GNU Affero General Public License v3.0
Project Creator : Barsonax

public void Start()
		{
			_disposed = false;
			while (!_disposed)
			{
				_waitHandle.WaitOne();
				try
				{
					_processer.Process(_workItem);
					_onCompleted?.Invoke(_workItem);
				}
				catch (Exception ex)
				{
					Debug.WriteLine(ex);
					Debugger.Break();
				}
				_waitHandle.Reset();
				IsBusy = false;
			}
		}

19 View Source File : Runner.cs
License : MIT License
Project Creator : actions

public async Task<int> ExecuteCommand(CommandSettings command)
        {
            try
            {
                VssUtil.InitializeVssClientSettings(HostContext.UserAgents, HostContext.WebProxy);

                _inConfigStage = true;
                _completedCommand.Reset();
                _term.CancelKeyPress += CtrlCHandler;

                //register a SIGTERM handler
                HostContext.Unloading += Runner_Unloading;

                // TODO Unit test to cover this logic
                Trace.Info(nameof(ExecuteCommand));
                var configManager = HostContext.GetService<IConfigurationManager>();

                // command is not required, if no command it just starts if configured

                // TODO: Invalid config prints usage

                if (command.Help)
                {
                    PrintUsage(command);
                    return Constants.Runner.ReturnCode.Success;
                }

                if (command.Version)
                {
                    _term.WriteLine(BuildConstants.RunnerPackage.Version);
                    return Constants.Runner.ReturnCode.Success;
                }

                if (command.Commit)
                {
                    _term.WriteLine(BuildConstants.Source.CommitHash);
                    return Constants.Runner.ReturnCode.Success;
                }

                if (command.Check)
                {
                    var url = command.GetUrl();
                    var pat = command.GetGitHubPersonalAccessToken(required: true);
                    var checkExtensions = HostContext.GetService<IExtensionManager>().GetExtensions<ICheckExtension>();
                    var sortedChecks = checkExtensions.OrderBy(x => x.Order);
                    foreach (var check in sortedChecks)
                    {
                        _term.WriteLine($"**********************************************************************************************************************");
                        _term.WriteLine($"**  Check:               {check.CheckName}");
                        _term.WriteLine($"**  Description:         {check.CheckDescription}");
                        _term.WriteLine($"**********************************************************************************************************************");
                        var result = await check.RunCheck(url, pat);
                        if (!result)
                        {
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**                                            F A I L                                                               **");
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**********************************************************************************************************************");
                            _term.WriteLine($"** Log: {check.CheckLog}");
                            _term.WriteLine($"** Help Doc: {check.HelpLink}");
                            _term.WriteLine($"**********************************************************************************************************************");
                        }
                        else
                        {
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**                                            P A S S                                                               **");
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**********************************************************************************************************************");
                            _term.WriteLine($"** Log: {check.CheckLog}");
                            _term.WriteLine($"**********************************************************************************************************************");
                        }

                        _term.WriteLine();
                        _term.WriteLine();
                    }

                    return Constants.Runner.ReturnCode.Success;
                }

                // Configure runner prompt for args if not supplied
                // Unattended configure mode will not prompt for args if not supplied and error on any missing or invalid value.
                if (command.Configure)
                {
                    try
                    {
                        await configManager.ConfigureAsync(command);
                        return Constants.Runner.ReturnCode.Success;
                    }
                    catch (Exception ex)
                    {
                        Trace.Error(ex);
                        _term.WriteError(ex.Message);
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }
                }

                // remove config files, remove service, and exit
                if (command.Remove)
                {
                    try
                    {
                        await configManager.UnconfigureAsync(command);
                        return Constants.Runner.ReturnCode.Success;
                    }
                    catch (Exception ex)
                    {
                        Trace.Error(ex);
                        _term.WriteError(ex.Message);
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }
                }

                _inConfigStage = false;

                // warmup runner process (JIT/CLR)
                // In scenarios where the runner is single use (used and then thrown away), the system provisioning the runner can call `Runner.Listener --warmup` before the machine is made available to the pool for use.
                // this will optimizes the runner process startup time.
                if (command.Warmup)
                {
                    var binDir = HostContext.GetDirectory(WellKnownDirectory.Bin);
                    foreach (var replacedemblyFile in Directory.EnumerateFiles(binDir, "*.dll"))
                    {
                        try
                        {
                            Trace.Info($"Load replacedembly: {replacedemblyFile}.");
                            var replacedembly = replacedembly.LoadFrom(replacedemblyFile);
                            var types = replacedembly.GetTypes();
                            foreach (Type loadedType in types)
                            {
                                try
                                {
                                    Trace.Info($"Load methods: {loadedType.FullName}.");
                                    var methods = loadedType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                                    foreach (var method in methods)
                                    {
                                        if (!method.IsAbstract && !method.ContainsGenericParameters)
                                        {
                                            Trace.Verbose($"Prepare method: {method.Name}.");
                                            RuntimeHelpers.PrepareMethod(method.MethodHandle);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Trace.Error(ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.Error(ex);
                        }
                    }

                    return Constants.Runner.ReturnCode.Success;
                }

                RunnerSettings settings = configManager.LoadSettings();

                var store = HostContext.GetService<IConfigurationStore>();
                bool configuredreplacedervice = store.IsServiceConfigured();

                // Run runner
                if (command.Run) // this line is current break machine provisioner.
                {
                    // Error if runner not configured.
                    if (!configManager.IsConfigured())
                    {
                        _term.WriteError("Runner is not configured.");
                        PrintUsage(command);
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }

                    Trace.Verbose($"Configured as service: '{configuredreplacedervice}'");

                    //Get the startup type of the runner i.e., autostartup, service, manual
                    StartupType startType;
                    var startupTypereplacedtring = command.GetStartupType();
                    if (string.IsNullOrEmpty(startupTypereplacedtring) && configuredreplacedervice)
                    {
                        // We need try our best to make the startup type accurate
                        // The problem is coming from runner autoupgrade, which result an old version service host binary but a newer version runner binary
                        // At that time the servicehost won't preplaced --startuptype to Runner.Listener while the runner is actually running as service.
                        // We will guess the startup type only when the runner is configured as service and the guess will based on whether STDOUT/STDERR/STDIN been redirect or not
                        Trace.Info($"Try determine runner startup type base on console redirects.");
                        startType = (Console.IsErrorRedirected && Console.IsInputRedirected && Console.IsOutputRedirected) ? StartupType.Service : StartupType.Manual;
                    }
                    else
                    {
                        if (!Enum.TryParse(startupTypereplacedtring, true, out startType))
                        {
                            Trace.Info($"Could not parse the argument value '{startupTypereplacedtring}' for StartupType. Defaulting to {StartupType.Manual}");
                            startType = StartupType.Manual;
                        }
                    }

                    Trace.Info($"Set runner startup type - {startType}");
                    HostContext.StartupType = startType;

                    if (command.RunOnce)
                    {
                        _term.WriteLine("Warning: '--once' is going to be deprecated in the future, please consider using '--ephemeral' during runner registration.", ConsoleColor.Yellow);
                        _term.WriteLine("https://docs.github.com/en/actions/hosting-your-own-runners/autoscaling-with-self-hosted-runners#using-ephemeral-runners-for-autoscaling", ConsoleColor.Yellow);
                    }

                    // Run the runner interactively or as service
                    return await RunAsync(settings, command.RunOnce || settings.Ephemeral);
                }
                else
                {
                    PrintUsage(command);
                    return Constants.Runner.ReturnCode.Success;
                }
            }
            finally
            {
                _term.CancelKeyPress -= CtrlCHandler;
                HostContext.Unloading -= Runner_Unloading;
                _completedCommand.Set();
            }
        }

19 View Source File : UDPClient.cs
License : MIT License
Project Creator : BlazorPlus

public byte[] Read(TimeSpan timeout)
		{
		//if (_removed) throw (new InvalidOperationException());

		READBUFF:

			lock (_packs)
			{
				if (_packs.Count > 0)
				{
					return _packs.Dequeue();
				}

				if (_removed)
					return null;

				_mre.Reset();
			}

			bool waited = _mre.WaitOne(timeout);
			if (!waited)
				return null;// throw (new TimeoutException());
			goto READBUFF;
		}

19 View Source File : EventLogReader.cs
License : MIT License
Project Creator : akpaevj

public EventLogItem ReadNextEventLogItem(CancellationToken cancellationToken = default)
        {
            if (_lgpReader == null)
                SetNextLgpReader();

            if (_settings.LiveMode && _lgpFilesWatcher == null)
                StartLgpFilesWatcher();

            EventLogItem item = null;

            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    item = _lgpReader.ReadNextEventLogItem(cancellationToken);
                }
                catch (ObjectDisposedException)
                {
                    item = null;
                    _lgpReader = null;
                    break;
                }

                if (item == null)
                {
                    var newReader = SetNextLgpReader();

                    if (_settings.LiveMode)
                    {
                        if (!newReader)
                        {
                            _lgpChangedCreated.Reset();

                            var waitHandle = WaitHandle.WaitAny(
                                new[] {_lgpChangedCreated, cancellationToken.WaitHandle}, _settings.ReadingTimeout);

                            if (_settings.ReadingTimeout != Timeout.Infinite && waitHandle == WaitHandle.WaitTimeout)
                                throw new EventLogReaderTimeoutException();

                            _lgpChangedCreated.Reset();
                        }
                    }
                    else
                    {
                        if (!newReader)
                            break;
                    }
                }
                else
                {
                    _settings.ItemId++;
                    item.Id = _settings.ItemId;

                    break;
                }
            }

            return item;
        }

19 View Source File : SampleMultiThreading.cs
License : MIT License
Project Creator : 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 View Source File : Worker.cs
License : MIT License
Project Creator : actions

public async Task<int> RunAsync(string pipeIn, string pipeOut)
        {
            try
            {
                // Setup way to handle SIGTERM/unloading signals
                _completedCommand.Reset();
                HostContext.Unloading += Worker_Unloading;

                // Validate args.
                ArgUtil.NotNullOrEmpty(pipeIn, nameof(pipeIn));
                ArgUtil.NotNullOrEmpty(pipeOut, nameof(pipeOut));
                VssUtil.InitializeVssClientSettings(HostContext.UserAgents, HostContext.WebProxy);
                var jobRunner = HostContext.CreateService<IJobRunner>();

                using (var channel = HostContext.CreateService<IProcessChannel>())
                using (var jobRequestCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(HostContext.RunnerShutdownToken))
                using (var channelTokenSource = new CancellationTokenSource())
                {
                    // Start the channel.
                    channel.StartClient(pipeIn, pipeOut);

                    // Wait for up to 30 seconds for a message from the channel.
                    HostContext.WritePerfCounter("WorkerWaitingForJobMessage");
                    Trace.Info("Waiting to receive the job message from the channel.");
                    WorkerMessage channelMessage;
                    using (var csChannelMessage = new CancellationTokenSource(_workerStartTimeout))
                    {
                        channelMessage = await channel.ReceiveAsync(csChannelMessage.Token);
                    }

                    // Deserialize the job message.
                    Trace.Info("Message received.");
                    ArgUtil.Equal(MessageType.NewJobRequest, channelMessage.MessageType, nameof(channelMessage.MessageType));
                    ArgUtil.NotNullOrEmpty(channelMessage.Body, nameof(channelMessage.Body));
                    var jobMessage = StringUtil.ConvertFromJson<Pipelines.AgentJobRequestMessage>(channelMessage.Body);
                    ArgUtil.NotNull(jobMessage, nameof(jobMessage));
                    HostContext.WritePerfCounter($"WorkerJobMessageReceived_{jobMessage.RequestId.ToString()}");

                    // Initialize the secret masker and set the thread culture.
                    InitializeSecretMasker(jobMessage);
                    SetCulture(jobMessage);

                    // Start the job.
                    Trace.Info($"Job message:{Environment.NewLine} {StringUtil.ConvertToJson(jobMessage)}");
                    Task<TaskResult> jobRunnerTask = jobRunner.RunAsync(jobMessage, jobRequestCancellationToken.Token);

                    // Start listening for a cancel message from the channel.
                    Trace.Info("Listening for cancel message from the channel.");
                    Task<WorkerMessage> channelTask = channel.ReceiveAsync(channelTokenSource.Token);

                    // Wait for one of the tasks to complete.
                    Trace.Info("Waiting for the job to complete or for a cancel message from the channel.");
                    Task.WaitAny(jobRunnerTask, channelTask);
                    // Handle if the job completed.
                    if (jobRunnerTask.IsCompleted)
                    {
                        Trace.Info("Job completed.");
                        channelTokenSource.Cancel(); // Cancel waiting for a message from the channel.
                        return TaskResultUtil.TranslateToReturnCode(await jobRunnerTask);
                    }

                    // Otherwise a cancel message was received from the channel.
                    Trace.Info("Cancellation/Shutdown message received.");
                    channelMessage = await channelTask;
                    switch (channelMessage.MessageType)
                    {
                        case MessageType.CancelRequest:
                            jobRequestCancellationToken.Cancel();   // Expire the host cancellation token.
                            break;
                        case MessageType.RunnerShutdown:
                            HostContext.ShutdownRunner(ShutdownReason.UserCancelled);
                            break;
                        case MessageType.OperatingSystemShutdown:
                            HostContext.ShutdownRunner(ShutdownReason.OperatingSystemShutdown);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException(nameof(channelMessage.MessageType), channelMessage.MessageType, nameof(channelMessage.MessageType));
                    }

                    // Await the job.
                    return TaskResultUtil.TranslateToReturnCode(await jobRunnerTask);
                }
            }
            finally
            {
                HostContext.Unloading -= Worker_Unloading;
                _completedCommand.Set();
            }
        }

19 View Source File : SuperIndexer.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public void EndTransaction()
        {
            Task.Run(async () =>
            {
                Debug.WriteLine("Ending Super Indexer Transaction...");

                var result = this.WaitingOnGroupAndChatListings.WaitOne(TimeSpan.FromSeconds(10));

                if (!result)
                {
                    Debug.WriteLine("No group list available, loading new...");

                    var client = this.GroupsAndChats.FirstOrDefault()?.Client;
                    if (client == null)
                    {
                        return;
                    }

                    await client.GetGroupsAsync();
                    await client.GetChatsAsync();
                    this.GroupsAndChats = Enumerable.Concat<IMessageContainer>(client.Groups(), client.Chats());
                }

                this.OutdatedGroupIdList = this.CheckForOutdatedCache(this.GroupsAndChats);

                Debug.WriteLine("Dirty groups computed, count " + this.OutdatedGroupIdList.Count);

                using (var context = this.CacheManager.OpenNewContext())
                {
                    // Update Group and Chat metadata in cache
                    if (DateTime.Now.Subtract(this.LastMetadataUpdate) > this.SettingsManager.CoreSettings.MetadataCacheInterval)
                    {
                        this.LastMetadataUpdate = DateTime.Now;

                        // Remove old metadata. Doing a removal and addition in the same cycle was causing
                        // OtherUserId foreign key for Chats to be null. Doing true updates with cascading deletes
                        // should be possible, but this can be done easily in SQLite without any further migrations (GMDC 33.0.3)
                        foreach (var metaData in this.GroupsAndChats)
                        {
                            if (metaData is Group groupMetadata)
                            {
                                var existing = context.GroupMetadata
                                    .Include(g => g.Members)
                                    .FirstOrDefault(g => g.Id == groupMetadata.Id);
                                if (existing != null)
                                {
                                    foreach (var member in existing.Members)
                                    {
                                        context.Remove(member);
                                    }

                                    context.GroupMetadata.Remove(existing);
                                }
                            }
                            else if (metaData is Chat chatMetadata)
                            {
                                var existingChat = context.ChatMetadata.FirstOrDefault(c => c.Id == metaData.Id);
                                if (existingChat != null)
                                {
                                    context.Remove(existingChat);
                                }

                                var existingMember = context.Find<Member>(chatMetadata.OtherUser.Id);
                                if (existingMember != null)
                                {
                                    context.Remove(existingMember);
                                }
                            }
                        }

                        context.SaveChanges();

                        foreach (var addMetaData in this.GroupsAndChats)
                        {
                            context.Add(addMetaData);
                        }

                        context.SaveChanges();
                    }

                    // Process updates for each group and chat
                    var fullyUpdatedGroupIds = new List<string>();
                    foreach (var id in this.GroupUpdates.Keys)
                    {
                        var messages = this.GroupUpdates[id];
                        var groupState = context.IndexStatus.Find(id);
                        if (groupState == null)
                        {
                            // No cache status exists for this group. Force a full re-index.
                        }
                        else if (this.OutdatedGroupIdList.Contains(id))
                        {
                            var availableMessageIds = messages.Select(m => long.Parse(m.Id)).ToList();
                            var messageContainer = this.GroupsAndChats.FirstOrDefault(c => c.Id == id);

                            long.TryParse(groupState.LastIndexedId, out var lastIndexId);
                            if (availableMessageIds.Contains(lastIndexId))
                            {
                                // All new messages have already been loaded and are ready to index.
                                var newMessages = new List<Message>();
                                var newLastIndexId = lastIndexId;
                                foreach (var msg in messages)
                                {
                                    if (long.TryParse(msg.Id, out var messageId) && messageId > lastIndexId)
                                    {
                                        newMessages.Add(msg);

                                        if (messageId > newLastIndexId)
                                        {
                                            newLastIndexId = messageId;
                                        }
                                    }
                                }

                                context.AddMessages(newMessages);
                                groupState.LastIndexedId = newLastIndexId.ToString();
                                context.SaveChanges();
                                fullyUpdatedGroupIds.Add(id);
                            }
                        }
                    }

                    Debug.WriteLine("In place deltas applied, resolved " + fullyUpdatedGroupIds.Count);

                    // Preplaced 2, go through all originally outdated chats and run the complete re-index task on them
                    // if they couldn't be automatically updated with available messages.
                    foreach (var id in this.OutdatedGroupIdList)
                    {
                        if (!fullyUpdatedGroupIds.Contains(id))
                        {
                            var container = this.GroupsAndChats.FirstOrDefault(c => c.Id == id);
                            var cts = new CancellationTokenSource();

                            Debug.WriteLine("Full index scan required for " + container.Name);

                            // Don't start multiple overlapping indexing tasks.
                            var existingScan = this.TaskManager.RunningTasks.FirstOrDefault(t => t.Tag == id);
                            if (existingScan == null)
                            {
                                this.TaskManager.AddTask(
                                    $"Indexing {container.Name}",
                                    id,
                                    this.IndexGroup(container, cts),
                                    cts);
                            }
                        }
                    }
                }

                this.GroupUpdates.Clear();
                this.WaitingOnGroupAndChatListings.Reset();
            });
        }

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 : LogsMessageGroupingExtensionUC.cs
License : MIT License
Project Creator : Analogy-LogViewer

private void AddExtraColumnsIfNeededToTable(DataTable table, GridView view, replacedogyLogMessage message)
        {
            if (message.AdditionalInformation != null && message.AdditionalInformation.Any() &&
                Settings.CheckAdditionalInformation)
            {
                foreach (KeyValuePair<string, string> info in message.AdditionalInformation)
                {
                    if (!table.Columns.Contains(info.Key))
                    {

                        if (!InvokeRequired)
                        {
                            if (!view.Columns.Select(g => g.FieldName).Contains(info.Key))
                            {
                                view.Columns.Add(new GridColumn() { Caption = info.Key, FieldName = info.Key, Name = info.Key, Visible = true });
                                table.Columns.Add(info.Key);
                            }

                        }
                        else
                        {
                            BeginInvoke(new MethodInvoker(() =>
                            {
                                if (!view.Columns.Select(g => g.FieldName).Contains(info.Key))
                                {
                                    view.Columns.Add(new GridColumn()
                                    { Caption = info.Key, FieldName = info.Key, Name = info.Key, Visible = true });
                                    table.Columns.Add(info.Key);
                                }
                                columnAdderSync.Set();
                            }));
                            columnAdderSync.WaitOne();
                            columnAdderSync.Reset();

                        }
                    }
                }
            }


        }

19 View Source File : SkinnedState.cs
License : MIT License
Project Creator : AmplifyCreations

internal override void UpdateTransform( CommandBuffer updateCB, bool starting )
	{
		if ( !m_initialized )
		{
			Initialize();
			return;
		}

		Profiler.BeginSample( "Skinned.Update" );

		if ( !starting && m_wasVisible )
			m_prevLocalToWorld = m_currLocalToWorld;

		bool isVisible = m_renderer.isVisible;

		if ( !m_error && ( isVisible || starting ) )
		{
			UpdateBones();

			m_starting = !m_wasVisible || starting;

			if ( !m_useFallback )
			{
				if ( !m_useGPU )
				{
					m_asyncUpdateSignal.Reset();
					m_asyncUpdateTriggered = true;
					m_owner.Instance.WorkerPool.EnqueueAsyncUpdate( this );
				}
				else
					UpdateVerticesGPU( updateCB, m_starting );
			}
			else
				UpdateVerticesFallback( m_starting );
		}

		if ( !m_useFallback )
		{
			m_currLocalToWorld = m_transform.localToWorldMatrix;
		}
		else
		{
		#if UNITY_2017_1_OR_NEWER
			m_currLocalToWorld = m_transform.localToWorldMatrix;
		#else
			m_currLocalToWorld = Matrix4x4.TRS( m_transform.position, m_transform.rotation, Vector3.one );
		#endif
		}

		if ( starting || !m_wasVisible )
			m_prevLocalToWorld = m_currLocalToWorld;

		m_wasVisible = isVisible;

		Profiler.EndSample();
	}

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

private IAsyncResult BeginExport(IExporter exporter, IBuffer buf, long start, long end)
	{
		exportFinishedEvent.Reset();

		ExportOperation eo = new ExportOperation(exporter, buf, start, end, ExportProgressCallback, OnExportFinished);

		CloseButton.Sensitive = false;
		ExportButton.Sensitive = false;

		// start export thread
		Thread exportThread = new Thread(eo.OperationThread);
		exportThread.IsBackground = true;
		exportThread.Start();

		return new ThreadedAsyncResult(eo, exportFinishedEvent, false);
	}

19 View Source File : DnaEnvironment.cs
License : MIT License
Project Creator : angelsix

private bool ReadNextLineOrExit(ref string readLine)
        {
            // Wait for either a read line or a cancel
            mReadLineResetEvent.Reset();

            // Flag indicating success
            var successful = false;

            // Store result
            var result = string.Empty;

            // Try and read the next line
            SafeTask.Run(() =>
            {
                // Read next line
                result = Console.ReadLine();

                // Flag success 
                successful = true;

                // Return function
                mReadLineResetEvent.Set();
            });

            // Wait for it to finish, or to be canceled
            mReadLineResetEvent.WaitOne();

            // If successful, set result
            if (successful)
                readLine = result;

            // Return if successful
            return successful;
        }

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();
                }
            }

public void WaitForRendering()
        {
            EventWaitHandle[] handles = new EventWaitHandle[] { SignalFromThread, DisposeSignal };
            int result = EventWaitHandle.WaitAny(handles);
            if (result == 0)
            {
                SignalFromThread.Reset();
            }
        }

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

public IAsyncResult ReplaceAll(byte[] ba, AsyncCallback ac)
	{
		if (dataBook.NPages == 0 || inUse) {
			ReplaceAllOperation op = new ReplaceAllOperation(strategy, null, ReplaceAllAsyncCallback, ba);
			return HandleProblematicOp(op, ac);
		}

		// DataBookFinder is already in use
		if (inUse)
			return null;

		inUse = true;

		userFindAsyncCallback = ac;

		DataView dv = ((DataViewDisplay)dataBook.CurrentPageWidget).View;

		// initialize strategy
		strategy.Buffer = dv.Buffer;
		strategy.Position = 0;

		SetUpReplaceAllProgressReport();

		ReplaceAllOperation rao = new ReplaceAllOperation(strategy, progressCallback, ReplaceAllAsyncCallback, ba);

		findFinishedEvent.Reset();

		// don't allow messing up with the buffer

		// start replace all thread
		Thread findThread = new Thread(rao.OperationThread);
		findThread.IsBackground = true;
		findThread.Start();

		return new ThreadedAsyncResult(rao, findFinishedEvent, false);
	}

19 View Source File : OnlineModsViewModel.cs
License : GNU General Public License v3.0
Project Creator : Artentus

private async Task RefreshOnlineModsAsync()
        {
            if (_refreshing) return;

            _refreshEvent.Reset();
            _refreshing = true;
            ModsLoaded = false;
            this.RaisePropertyChanged(nameof(ModsLoaded));
            LoadingErrorOccurred = false;
            this.RaisePropertyChanged(nameof(LoadingErrorOccurred));
            SelectedMod = null;

            // Avoid memory leak
            DisposeOnlineMods();

            try
            {
                _onlineMods = await LoadOnlineModsAsync();

                foreach (var mod in _onlineMods)
                    mod.ApplyFuzzyFilter(_filter);
            }
            catch (ApiException ex)
            {
                if (ex is ConnectFailureException)
                {
                    // Connection error
                    LoadingErrorOccurred = true;
                    this.RaisePropertyChanged(nameof(LoadingErrorOccurred));
                    ErrorMessageKey = "ConnectionError_Message";
                    this.RaisePropertyChanged(nameof(ErrorMessageKey));
                    Log.Error(ex, "Failed to connect to server");
                }
                else if (ex is TimeoutException)
                {
                    // Timeout
                    LoadingErrorOccurred = true;
                    this.RaisePropertyChanged(nameof(LoadingErrorOccurred));
                    ErrorMessageKey = "TimeoutError_Message";
                    this.RaisePropertyChanged(nameof(ErrorMessageKey));
                    Log.Error(ex, "Timeout while trying to connect to server");
                }
                else
                {
                    // Server error
                    LoadingErrorOccurred = true;
                    this.RaisePropertyChanged(nameof(LoadingErrorOccurred));
                    ErrorMessageKey = "ServerError_Message";
                    this.RaisePropertyChanged(nameof(ErrorMessageKey));
                    Log.Error(ex, "An unknown server error occurred");
                }

                _onlineMods = new List<OnlineModViewModel>(0);
            }

            OnlineMods = new CollectionView<OnlineModViewModel>(_onlineMods, SelectedComparer, FilterMod);
            this.RaisePropertyChanged(nameof(OnlineMods));

            RefreshFactorioVersions();

            ModsLoaded = true;
            this.RaisePropertyChanged(nameof(ModsLoaded));

            _refreshing = false;
            _refreshEvent.Set();
        }

19 View Source File : OVRNetwork.cs
License : MIT License
Project Creator : absurd-joy

public void Tick()
		{
			if (tcpClient == null || !tcpClient.Connected)
			{
				return;
			}

			if (readyReceiveDataEvent.WaitOne(TimeSpan.Zero))
			{
				if (tcpClient.GetStream().DataAvailable)
				{
					if (receivedBufferDataSize >= OVRNetwork.MaxBufferLength)
					{
						Debug.LogWarning("[OVRNetworkTcpClient] receive buffer overflow. It should not happen since we have the constraint on message size");
						Disconnect();
						return;
					}

					readyReceiveDataEvent.Reset();
					int maximumDataSize = OVRSystemPerfMetrics.MaxBufferLength - receivedBufferDataSize;

					tcpClient.GetStream().BeginRead(receivedBuffers[receivedBufferIndex], receivedBufferDataSize, maximumDataSize, new AsyncCallback(OnReadDataCallback), tcpClient.GetStream());
				}
			}
		}

19 View Source File : ModHandler.cs
License : MIT License
Project Creator : AstroTechies

public void UpdateAvailableVersionsFromIndexFiles()
        {
            IsUpdatingAvailableVersionsFromIndexFilesWaitHandler.Reset();
            Dictionary<Mod, Version> switchVersionInstructions = new Dictionary<Mod, Version>();
            foreach (Mod mod in Mods)
            {
                Version latestVersion = null;
                if (mod.AvailableVersions.Count > 0) latestVersion = mod.AvailableVersions[0];
                if (GlobalIndexFile.ContainsKey(mod.CurrentModData.ModID))
                {
                    IndexMod indexMod = GlobalIndexFile[mod.CurrentModData.ModID];
                    mod.AvailableVersions.AddRange(indexMod.AllVersions.Keys.Except(mod.AvailableVersions));
                    mod.AvailableVersions.Sort();
                    mod.AvailableVersions.Reverse();
                    latestVersion = mod.AvailableVersions[0];
                    //if (indexMod.LatestVersion != null) latestVersion = indexMod.LatestVersion;
                }

                if (mod.ForceLatest && latestVersion != null) switchVersionInstructions.Add(mod, latestVersion);
            }

            AMLUtils.InvokeUI(BaseForm.TableManager.Refresh);

            foreach (KeyValuePair<Mod, Version> entry in switchVersionInstructions)
            {
                BaseForm.SwitchVersionSync(entry.Key, entry.Value);
            }
            IsUpdatingAvailableVersionsFromIndexFilesWaitHandler.Set();
        }

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

public IAsyncResult BeginSave(ProgressCallback progressCallback, AsyncCallback ac) 
	{
		lock (LockObj) {		
			if (!fileOperationsAllowed) return null;
			
			saveFinishedEvent.Reset();
			userSaveAsyncCallback = ac;
			
			Thread saveThread = null;
			ThreadedAsyncResult tar = null;

			// decide whether to save in place or normally
			if (!fileBuf.IsResizable || this.Size == fileBuf.Size) {
				SaveInPlaceOperation sipo = new SaveInPlaceOperation(this, progressCallback, SaveInPlaceAsyncCallback, useGLibIdle);
				saveThread = new Thread(sipo.OperationThread);
				tar = new ThreadedAsyncResult(sipo, saveFinishedEvent, false);
			}
			else {
				SaveOperation so = new SaveOperation(this, TempFile.CreateName(tempDir), progressCallback, SaveAsyncCallback, useGLibIdle);
				saveThread = new Thread(so.OperationThread);
				tar = new ThreadedAsyncResult(so, saveFinishedEvent, false);
			}
			
			// don't allow messing up with the buffer
			// while we are saving
			// ...ReadAllowed is set in SaveOperation
			//this.ReadAllowed=false;
			this.ModifyAllowed = false;
			this.FileOperationsAllowed = false;
			
			this.EmitEvents = false;
			fsw.EnableRaisingEvents = false;
			
			// start save thread			
			saveThread.IsBackground = true;
			saveThread.Start();
			
			return tar;
		}
	}

19 View Source File : RegistryMonitor.cs
License : GNU General Public License v3.0
Project Creator : Avinch

public void Start()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(null, "This instance is already disposed");
            }

            lock (_threadLock)
            {
                if (!IsMonitoring)
                {
                    _eventTerminate.Reset();
                    _thread = new Thread(MonitorThread);
                    _thread.IsBackground = true;
                    _thread.Start();
                }
            }
        }

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 : FrameGrabber.cs
License : MIT License
Project Creator : Azure-Samples

protected void StartProcessing(TimeSpan frameGrabDelay, Func<DateTime> timestampFn)
        {
            OnProcessingStarting();

            _resetTrigger = true;
            _frameGrabTimer.Reset();
            _replacedysisTaskQueue = new BlockingCollection<Task<NewResultEventArgs>>();

            var timerIterations = 0;

            // Create a background thread that will grab frames in a loop.
            _producerTask = Task.Factory.StartNew(() =>
            {
                var frameCount = 0;
                while (!_stopping)
                {
                    LogMessage("Producer: waiting for timer to trigger frame-grab");

                    // Wait to get released by the timer. 
                    _frameGrabTimer.WaitOne();
                    LogMessage("Producer: grabbing frame...");

                    var startTime = DateTime.Now;

                    // Grab single frame. 
                    var timestamp = timestampFn();
                    Mat image = new Mat();
                    bool success = _reader.Read(image);

                    LogMessage("Producer: frame-grab took {0} ms", (DateTime.Now - startTime).Milliseconds);

                    if (!success)
                    {
                        // If we've reached the end of the video, stop here. 
                        if (_reader.CaptureType == CaptureType.File)
                        {
                            LogMessage("Producer: null frame from video file, stop!");
                            // This will call StopProcessing on a new thread.
                            var stopTask = StopProcessingAsync();
                            // Break out of the loop to make sure we don't try grabbing more
                            // frames. 
                            break;
                        }
                        else
                        {
                            // If failed on live camera, try again. 
                            LogMessage("Producer: null frame from live camera, continue!");
                            continue;
                        }
                    }

                    // Package the image for submission.
                    VideoFrameMetadata meta;
                    meta.Index = frameCount;
                    meta.Timestamp = timestamp;
                    VideoFrame vframe = new VideoFrame(image, meta);

                    // Raise the new frame event
                    LogMessage("Producer: new frame provided, should replacedyze? Frame num: {0}", meta.Index);
                    OnNewFrameProvided(vframe);

                    if (_replacedysisPredicate(vframe))
                    {
                        LogMessage("Producer: replacedyzing frame");

                        // Call the replacedysis function on a threadpool thread
                        var replacedysisTask = DoreplacedyzeFrame(vframe);

                        LogMessage("Producer: adding replacedysis task to queue {0}", replacedysisTask.Id);

                        // Push the frame onto the queue
                        _replacedysisTaskQueue.Add(replacedysisTask);
                    }
                    else
                    {
                        LogMessage("Producer: not replacedyzing frame");
                    }

                    LogMessage("Producer: iteration took {0} ms", (DateTime.Now - startTime).Milliseconds);

                    ++frameCount;
                }

                LogMessage("Producer: stopping, destroy reader and timer");
                _replacedysisTaskQueue.CompleteAdding();

                // We reach this point by breaking out of the while loop. So we must be stopping. 
                _reader.Dispose();
                _reader = null;

                // Make sure the timer stops, then get rid of it. 
                var h = new ManualResetEvent(false);
                _timer.Dispose(h);
                h.WaitOne();
                _timer = null;

                LogMessage("Producer: stopped");
            }, TaskCreationOptions.LongRunning);

            _consumerTask = Task.Factory.StartNew(async () =>
            {
                while (!_replacedysisTaskQueue.IsCompleted)
                {
                    LogMessage("Consumer: waiting for task to get added");

                    // Get the next processing task. 
                    Task<NewResultEventArgs> nextTask = null;

                    // Blocks if m_replacedysisTaskQueue.Count == 0
                    // IOE means that Take() was called on a completed collection.
                    // Some other thread can call CompleteAdding after we preplaced the
                    // IsCompleted check but before we call Take. 
                    // In this example, we can simply catch the exception since the 
                    // loop will break on the next iteration.
                    // See https://msdn.microsoft.com/en-us/library/dd997371(v=vs.110).aspx
                    try
                    {
                        nextTask = _replacedysisTaskQueue.Take();
                    }
                    catch (InvalidOperationException) { }

                    if (nextTask != null)
                    {
                        // Block until the result becomes available. 
                        LogMessage("Consumer: waiting for next result to arrive for task {0}", nextTask.Id);
                        var result = await nextTask;

                        // Raise the new result event. 
                        LogMessage("Consumer: got result for frame {0}. {1} tasks in queue", result.Frame.Metadata.Index, _replacedysisTaskQueue.Count);
                        OnNewResultAvailable(result);
                    }
                }

                LogMessage("Consumer: stopped");
            }, TaskCreationOptions.LongRunning);

            // Set up a timer object that will trigger the frame-grab at a regular interval.
            _timer = new Timer(async s /* state */ =>
            {
                await _timerMutex.WaitAsync();
                try
                {
                    // If the handle was not reset by the producer, then the frame-grab was missed.
                    bool missed = _frameGrabTimer.WaitOne(0);

                    _frameGrabTimer.Set();

                    if (missed)
                    {
                        LogMessage("Timer: missed frame-grab {0}", timerIterations - 1);
                    }
                    LogMessage("Timer: grab frame num {0}", timerIterations);
                    ++timerIterations;
                }
                finally
                {
                    _timerMutex.Release();
                }
            }, null, TimeSpan.Zero, frameGrabDelay);

            OnProcessingStarted();
        }

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

public IAsyncResult FindNext(AsyncCallback ac)
	{
		if (dataBook.NPages == 0 || inUse) {
			FindNextOperation op = new FindNextOperation(strategy, null, FindAsyncCallback);
			return HandleProblematicOp(op, ac);
		}

		inUse = true;

		userFindAsyncCallback = ac;
		findFinishedEvent.Reset();

		// if this is the first time we are checking
		// for a valid pattern, emit the event
		if (firstTime == true && strategy.Pattern.Length > 0) {
			firstTime = false;
			if (FirstFind != null)
				FirstFind();
		} // is pattern acceptable?
		else if (strategy.Pattern.Length == 0)
			return null;

		DataView dv = ((DataViewDisplay)dataBook.CurrentPageWidget).View;

		strategy.Buffer = dv.Buffer;

		// decide where to start searching from
		if (!dv.Selection.IsEmpty())
			strategy.Position = dv.Selection.Start + 1;
		else
			strategy.Position = dv.CursorOffset;

		SetUpFindProgressReport();


		FindNextOperation fno = new FindNextOperation(strategy, progressCallback, FindAsyncCallback);

		// lock the buffer, so user can't modify it while
		// searching
		strategy.Buffer.ModifyAllowed = false;
		strategy.Buffer.FileOperationsAllowed = false;

		// start find thread
		Thread findThread = new Thread(fno.OperationThread);
		findThread.IsBackground = true;
		findThread.Start();

		return new ThreadedAsyncResult(fno, findFinishedEvent, false);
	}

19 View Source File : MultithreadedWorkerQueue.cs
License : GNU Affero General Public License v3.0
Project Creator : Barsonax

public void Stop()
        {
            _stopManualResetEvent.Reset();
        }

19 View Source File : CelesteNetConnection.cs
License : MIT License
Project Creator : 0x0ade

protected virtual void ThreadLoop() {
            try {
                while (Con.IsAlive) {
                    DedupeTimestamp++;

                    int waited = 0;
                    if (Interlocked.CompareExchange(ref QueueCount, 0, 0) == 0)
                        waited = WaitHandle.WaitAny(EventHandles, 1000);

                    if ((waited == WaitHandle.WaitTimeout || DedupeTimestamp % 10 == 0) && LastSent.Count > 0) {
                        for (int i = Dedupes.Count - 1; i >= 0; --i) {
                            DataDedupe slot = Dedupes[i];
                            if (!slot.Update(DedupeTimestamp)) {
                                Dedupes.RemoveAt(i);
                                if (LastSent.TryGetValue(slot.Type, out Dictionary<uint, DataDedupe>? slotByID)) {
                                    slotByID.Remove(slot.ID);
                                    if (slotByID.Count == 0) {
                                        LastSent.Remove(slot.Type);
                                    }
                                }
                            }
                        }
                    }

                    if (!Con.IsAlive)
                        return;

                    DateTime now = DateTime.UtcNow;

                    while (Interlocked.CompareExchange(ref QueueCount, 0, 0) != 0) {
                        DataType? data;
                        lock (QueueLock) {
                            int next = QueueSendNext;
                            data = Queue[next];
                            Queue[next] = null;
                            QueueSendNext = (next + 1) % Queue.Length;
                            Interlocked.Decrement(ref QueueCount);
                        }

                        if (data == null)
                            continue;

                        if (data is DataInternalDisconnect) {
                            Con.Dispose();
                            return;
                        }

                        if ((data.DataFlags & DataFlags.OnlyLatest) == DataFlags.OnlyLatest) {
                            string type = data.GetTypeID(Con.Data);
                            uint id = data.GetDuplicateFilterID();

                            lock (QueueLock) {
                                int next = QueueSendNext;
                                int count = Interlocked.CompareExchange(ref QueueCount, 0, 0);
                                int length = Queue.Length;
                                for (int ii = 0; ii < count; ii++) {
                                    int i = (next + ii) % length;
                                    DataType? d = Queue[i];
                                    if (d != null && d.GetTypeID(Con.Data) == type && d.GetDuplicateFilterID() == id) {
                                        data = d;
                                        Queue[i] = null;
                                    }
                                }
                            }
                        }

                        if ((data.DataFlags & DataFlags.SkipDuplicate) == DataFlags.SkipDuplicate) {
                            string type = data.GetTypeID(Con.Data);
                            uint id = data.GetDuplicateFilterID();

                            if (!LastSent.TryGetValue(type, out Dictionary<uint, DataDedupe>? slotByID))
                                LastSent[type] = slotByID = new();

                            if (slotByID.TryGetValue(id, out DataDedupe? slot)) {
                                if (slot.Data.ConsideredDuplicate(data))
                                    continue;
                                slot.Data = data;
                                slot.Timestamp = DedupeTimestamp;
                                slot.Iterations = 0;
                            } else {
                                Dedupes.Add(slotByID[id] = new(type, id, data, DedupeTimestamp));
                            }

                        }

                        Con.SendRaw(this, data);

                        if ((data.DataFlags & DataFlags.Update) == DataFlags.Update)
                            LastUpdate = now;
                        else
                            LastNonUpdate = now;
                    }

                    if (Con.SendStringMap) {
                        List<Tuple<string, int>> added = Strings.PromoteRead();
                        if (added.Count > 0) {
                            foreach (Tuple<string, int> mapping in added)
                                Con.SendRaw(this, new DataLowLevelStringMapping {
                                    IsUpdate = SendStringMapUpdate,
                                    StringMap = Strings.Name,
                                    Value = mapping.Item1,
                                    ID = mapping.Item2
                                });
                            if (SendStringMapUpdate)
                                LastUpdate = now;
                            else
                                LastNonUpdate = now;
                        }
                    }

                    if (Con.SendKeepAlive) {
                        if (SendKeepAliveUpdate && (now - LastUpdate).TotalSeconds >= 1D) {
                            Con.SendRaw(this, new DataLowLevelKeepAlive {
                                IsUpdate = true
                            });
                            LastUpdate = now;
                        }
                        if (SendKeepAliveNonUpdate && (now - LastNonUpdate).TotalSeconds >= 1D) {
                            Con.SendRaw(this, new DataLowLevelKeepAlive {
                                IsUpdate = false
                            });
                            LastNonUpdate = now;
                        }
                    }

                    Con.SendRawFlush();

                    lock (QueueLock)
                        if (Interlocked.CompareExchange(ref QueueCount, 0, 0) == 0)
                            Event.Reset();
                }

            } catch (ThreadInterruptedException) {

            } catch (ThreadAbortException) {

            } catch (Exception e) {
                if (!(e is IOException) && !(e is ObjectDisposedException))
                    Logger.Log(LogLevel.CRI, "conqueue", $"Failed sending data:\n{e}");

                Con.Dispose();

            } finally {
                Event.Dispose();
            }
        }

19 View Source File : UDPClient.cs
License : MIT License
Project Creator : BlazorPlus

public int Read(byte[] buffer, int offset, int count, TimeSpan timeout)
		{
			//if (_removed) throw (new InvalidOperationException());

			int rc = 0;

		READBUFF:

			if (_buff != null)
			{
				int rl = Math.Min(count - rc, _buff.Length - _bidx);
				Buffer.BlockCopy(_buff, _bidx, buffer, offset + rc, rl);
				rc += rl;
				_bidx += rl;
				if (_bidx == _buff.Length)
					_buff = null;
			}

			if (rc == count)
				return rc;

			lock (_packs)
			{
				if (_packs.Count > 0)
				{
					_buff = _packs.Dequeue();
					_bidx = 0;
					goto READBUFF;
				}

				if (rc > 0)
					return rc;//don't wait

				if (_removed)
					return rc;

				_mre.Reset();
			}

			_mre.WaitOne(timeout);
			goto READBUFF;
		}

19 View Source File : WaveOut.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public bool Play()
        {
            lock(this)
            {
                m_PlayEvent.Reset();
                m_Playing = WaveNative.waveOutWrite(m_WaveOut, ref m_Header, Marshal.SizeOf(m_Header)) == WaveNative.MMSYSERR_NOERROR;
                return m_Playing;
            }
        }

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 : 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 : RtmpServer.cs
License : MIT License
Project Creator : a1q123456

public Task StartAsync(CancellationToken ct = default)
        {
            if (Started)
            {
                throw new InvalidOperationException("already started");
            }
            _webSocketServer?.Start(c =>
            {
                var session = new WebSocketSession(c, _webSocketOptions);
                c.OnOpen = session.HandleOpen;
                c.OnClose = session.HandleClose;
                c.OnMessage = session.HandleMessage;
            });

            if (_webSocketServer != null)
            {
                CancellationTokenRegistration reg = default;
                reg = ct.Register(() =>
                {
                    reg.Dispose();
                    _webSocketServer.Dispose();
                    _webSocketServer = new WebSocketServer(_webSocketOptions.BindEndPoint.ToString());
                });
            }
            Started = true;
            var ret = new TaskCompletionSource<int>();
            var t = new Thread(o =>
            {
                try
                {
                    while (!ct.IsCancellationRequested)
                    {
                        try
                        {
                            _allDone.Reset();
                            _listener.BeginAccept(new AsyncCallback(ar =>
                            {
                                AcceptCallback(ar, ct);
                            }), _listener);
                            while (!_allDone.WaitOne(1))
                            {
                                ct.ThrowIfCancellationRequested();
                            }
                        }
                        catch (OperationCanceledException)
                        {
                            throw;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.ToString());
                        }
                    }
                }
                catch (OperationCanceledException) { }
                finally
                {
                    ret.SetResult(1);
                }
            });

            t.Start();
            return ret.Task;
        }

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 : 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 : ProcessReader.cs
License : Apache License 2.0
Project Creator : AmpScm

public string ReadLine()
        {
            string retval;
            lock(this.queue)
            {
                Debug.WriteLine( "ReadLine() waiting on event", "Ankh" );
                this.queueNonEmpty.WaitOne();
                Debug.WriteLine( "ReadLine() event signaled", "Ankh" );

                retval = (string)this.queue.Dequeue();
                if ( this.queue.Count == 0 )
                {
                    Debug.WriteLine( "ReadLine() resetting event: queue is empty" );
                    this.queueNonEmpty.Reset();
                }
            }
            return retval;
        }

See More Examples