コード例 #1
0
        public void AddToOrderedChannel(Packet message)
        {
            try
            {
                if (_cancellationToken.Token.IsCancellationRequested)
                {
                    return;
                }

                if (message.ReliabilityHeader.OrderingIndex <= _lastOrderingIndex)
                {
                    return;
                }

                lock (_eventSync)
                {
                    //Log.Debug($"Received packet {message.Id} with ordering index={message.ReliabilityHeader.OrderingIndex}. Current index={_lastOrderingIndex}");

                    //if (_orderingBufferQueue.Count == 0 && message.ReliabilityHeader.OrderingIndex == _lastOrderingIndex + 1)
                    //{
                    //	if (_orderedQueueProcessingThread != null)
                    //	{
                    //		// Remove the thread again? But need to deal with cancellation token, so not entirely easy.
                    //		// Needs refactoring of the processing thread first.
                    //	}
                    //	_lastOrderingIndex = message.ReliabilityHeader.OrderingIndex;
                    //	HandlePacket(message);
                    //	return;
                    //}

                    if (_orderedQueueProcessingThread == null)
                    {
                        _orderedQueueProcessingThread = new Thread(ProcessOrderedQueue)
                        {
                            IsBackground = true,
                            Name         = $"Ordering Thread [{EndPoint}]"
                        };
                        _orderedQueueProcessingThread.Start();
                        if (Log.IsDebugEnabled)
                        {
                            Log.Warn($"Started processing thread for {Username}");
                        }
                    }

                    _orderingBufferQueue.Enqueue(message.ReliabilityHeader.OrderingIndex, message);
                    if (message.ReliabilityHeader.OrderingIndex == _lastOrderingIndex + 1)
                    {
                        WaitHandle.SignalAndWait(_packetQueuedWaitEvent, _packetHandledWaitEvent);
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
コード例 #2
0
        private void WriteMain()
        {
            BinaryFormatter formatter = new BinaryFormatter();

            //byte[] frame = new byte[4];

            //outer loop
            while (!dispose)
            {
                LogDebugW(this + ": WriteMain() waiting for connection");
                WaitHandle.SignalAndWait(writerIsWaiting, writerShouldStart);
                LogDebugW(this + ": WriteMain() begin");

                SentSinceLastReconnect = 0;
                while (true)
                {
                    try
                    {
                        if (ConnectionIsActive)
                        {
                            //communication loop
                            //Log.Debug(this + ": WriteMain() waiting for next object");
                            object send = outbound.GetNext();
                            if (send == null)
                            {
                                if (outbound.IsDisposed)
                                {
                                    LogDebugW(this + ": WriteMain() interrupt (" + SentSinceLastReconnect + "). Outbound is disposed");
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            formatter.Serialize(stream, send);
                            SentSinceLastReconnect++;
                        }
                        else
                        {
                            LogDebugW(this + ": WriteMain() interrupt (" + SentSinceLastReconnect + "). Connection died");
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        LogDebugW(this + ": WriteMain() exception (" + SentSinceLastReconnect + ")");
                        Log.Error(ex);
                        client.Close();
                        break;
                    }
                }
                //Log.Debug(this + ": WriteMain() restart");
            }
        }
コード例 #3
0
        public static void SignalAndWait()
        {
            using (var eventToSignal = new AutoResetEvent(false))
                using (var eventToWait = new AutoResetEvent(false))
                {
                    eventToWait.Set();

                    Assert.IsTrue(WaitHandle.SignalAndWait(eventToSignal, eventToWait), "#1");
                    Assert.IsTrue(eventToSignal.WaitOne(), "#2");
                }
        }
コード例 #4
0
        private void Worker(object threadStarted)
        {
            try {
                SynchronizationContext.SetSynchronizationContext(new AnalysisSynchronizationContext(this));
                _scheduler = TaskScheduler.FromCurrentSynchronizationContext();
            } finally {
                ((AutoResetEvent)threadStarted).Set();
            }

            while (!_cancel.IsCancellationRequested)
            {
                IAnalyzable workItem;

                AnalysisPriority pri;
                lock (_queueLock) {
                    workItem     = GetNextItem(out pri);
                    _isAnalyzing = true;
                }
                var evt = AnalysisStarted;
                if (evt != null)
                {
                    evt(this, EventArgs.Empty);
                }

                if (workItem != null)
                {
                    var groupable = workItem as IGroupableAnalysisProjectEntry;
                    if (groupable != null)
                    {
                        bool added = _enqueuedGroups.Add(groupable.AnalysisGroup);
                        if (added)
                        {
                            Enqueue(new GroupAnalysis(groupable.AnalysisGroup, this), pri);
                        }

                        groupable.Analyze(_cancel.Token, true);
                    }
                    else
                    {
                        workItem.Analyze(_cancel.Token);
                    }
                }
                else
                {
                    _isAnalyzing = false;
                    WaitHandle.SignalAndWait(
                        _analyzer.QueueActivityEvent,
                        _workEvent
                        );
                }
            }
            _isAnalyzing = false;
        }
コード例 #5
0
 private void ChildThreadLoop()
 {
     childThreadHandle.Reset();
     childThreadHandle.WaitOne();
     while (running)
     {
         childThreadHandle.Reset();
         UpdateThread(time, deltaTime);
         WaitHandle.SignalAndWait(mainThreadHandle, childThreadHandle); //Signals one WaitHandle and waits on another.
     }
     WaitHandle.SignalAndWait(mainThreadHandle, childThreadHandle);
 }
コード例 #6
0
        public void Wait()
        {
            bool first = m_First.WaitOne(TimeSpan.Zero, false);

            if (first)
            {
                WaitHandle.SignalAndWait(m_Event1, m_Event2);
            }
            else
            {
                WaitHandle.SignalAndWait(m_Event2, m_Event1);
            }
        }
コード例 #7
0
ファイル: PlayerNetworkSession.cs プロジェクト: Polo1K/MiNET
        public void AddToProcessing(Package message)
        {
            try
            {
                if (_cancellationToken.Token.IsCancellationRequested)
                {
                    return;
                }

                bool forceOrder = Server.ForceOrderingForAll;

                if (!forceOrder)
                {
                    if (CryptoContext == null || CryptoContext.UseEncryption == false)
                    {
                        _lastSequenceNumber = message.OrderingIndex;
                        HandlePackage(message, this);
                        return;
                    }
                }

                lock (_eventSync)
                {
                    if (_queue.Count == 0 && message.OrderingIndex == _lastSequenceNumber + 1)
                    {
                        _lastSequenceNumber = message.OrderingIndex;
                        HandlePackage(message, this);
                        return;
                    }

                    if (_processingThread == null)
                    {
                        _processingThread = new Thread(ProcessQueueThread)
                        {
                            IsBackground = true
                        };
                        _processingThread.Start();
                        if (Log.IsDebugEnabled)
                        {
                            Log.Warn($"Started processing thread for {Username}");
                        }
                    }

                    _queue.Enqueue(message.OrderingIndex, message);
                    WaitHandle.SignalAndWait(_waitEvent, _mainWaitEvent);
                }
            }
            catch (Exception e)
            {
            }
        }
コード例 #8
0
            public void Update()
            {
                _mainWaitHandle = GetMainWaitHandle(this, ChildWaitHandle);

                while (!Stop)
                {
                    ChildWaitHandle.Reset();
                    DoneUpdate = false;

                    Data = _update.Invoke(Data);

                    DoneUpdate = true;
                    WaitHandle.SignalAndWait(_mainWaitHandle, ChildWaitHandle);
                }
            }
コード例 #9
0
    void ChildThreadLoop()
    {
        ChildThreadWait.Reset();
        ChildThreadWait.WaitOne();

        while (true)
        {
            ChildThreadWait.Reset();

            // Do Update

            // Debug.Log("testing threads");

            WaitHandle.SignalAndWait(MainThreadWait, ChildThreadWait);
        }
    }
コード例 #10
0
ファイル: GrassManager.cs プロジェクト: looki666/Green-Hell
 private void InitCellContentOnThread()
 {
     this.WorkerThreadWait.Reset();
     this.WorkerThreadWait.WaitOne();
     for (;;)
     {
         this.WorkerThreadWait.Reset();
         this.ThreadIsRunning = true;
         for (int i = 0; i < this.wt_cellindexListCount; i++)
         {
             this.InitCellContent(this.wt_cellindexList[i]);
         }
         this.ThreadIsRunning = false;
         WaitHandle.SignalAndWait(this.MainThreadWait, this.WorkerThreadWait);
     }
 }
コード例 #11
0
        protected override void ExecuteInternal()
        {
            ThreadPool.QueueUserWorkItem(_ =>
            {
                Thread.Sleep(Timeout.Infinite);
            });
            ThreadPool.QueueUserWorkItem(_ =>
            {
                Thread.Sleep(Timeout.Infinite);
            });

            Thread CreateDeadlockedThread(EventWaitHandle ewh1, EventWaitHandle ewh2)
            {
                var thread = new Thread(_ =>
                {
                    try
                    {
                        lock (ewh1)
                        {
                            WaitHandle.SignalAndWait(ewh1, ewh2);
                            Console.Green($"Thread {Thread.CurrentThread.ManagedThreadId} has aquired first lock");

                            lock (ewh2)
                            {
                                System.Console.WriteLine("We will never see this string");
                            }
                        }
                    }
                    catch (ThreadInterruptedException) { }
                });

                return(thread);
            }

            var are1 = new EventWaitHandle(false, EventResetMode.AutoReset);
            var are2 = new EventWaitHandle(false, EventResetMode.AutoReset);

            var thread1 = CreateDeadlockedThread(are1, are2);
            var thread2 = CreateDeadlockedThread(are2, are1);

            thread1.Start();
            thread2.Start();

            Console.WaitForContinue("Interrupt both threads");
            thread1.Interrupt();
            thread2.Interrupt();
        }
コード例 #12
0
ファイル: SingalWait.cs プロジェクト: dmgactive/cslearn
        public void Learn()
        {
            ewh = new EventWaitHandle(false, EventResetMode.AutoReset);

            for (int i = 0; i <= 4; i++)
            {
                Thread t = new Thread(new ParameterizedThreadStart(ThreadProc));
                t.Start(i);
            }

            while (Interlocked.Read(ref threadCount) < 5)
            {
                Thread.Sleep(500);
            }

            while (Interlocked.Read(ref threadCount) > 0)
            {
                Console.WriteLine("Press Enter to release a waiting thread.");
                Console.ReadLine();
                clearCount.Set();
                WaitHandle.SignalAndWait(ewh, clearCount);
                Console.WriteLine("loop again.");
            }
            Console.WriteLine();

            ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

            for (int i = 0; i <= 4; i++)
            {
                Thread t = new Thread(new ParameterizedThreadStart(ThreadProc));
                t.Start(i);
            }

            while (Interlocked.Read(ref threadCount) < 5)
            {
                Thread.Sleep(500);
            }

            Console.WriteLine("Press ENTER to release the waiting threads");
            Console.ReadLine();
            ewh.Set();
            ewh.Reset();
            Console.WriteLine("Press ENTER to release the waiting threads");
            Console.ReadLine();
            ewh.Set();
        }
コード例 #13
0
        void ChildThreadLoop()
        {
            // Reset the WaitHandle
            childThreadWait.Reset();
            // request to wait on a WaitHandle that is reset, which will block the thread until Set() is called on the WaitHandle, but in another thread
            childThreadWait.WaitOne();

            while (true)
            {
                childThreadWait.Reset();

                for (int i = 0; i < guards.Count; i++)
                {
                    myTopPos.x = transform.position.x;
                    myTopPos.y = transform.position.z;

                    otherTopPos.x = guards[i].transform.position.x;
                    otherTopPos.y = guards[i].transform.position.z;

                    myPos.x = transform.position.x;
                    myPos.y = guards[i].transform.position.y;
                    myPos.z = transform.position.z;

                    // if the player is within the vision range
                    if (Vector2.Distance(myTopPos, otherTopPos) < rangeOfVision)
                    {
                        // get the direction of the player's head...
                        targetDir = guards[i].transform.position - myPos;
                        //...if the angle between the looking dir of the cam and the player is less than the cone of vision, then you are inside the cone of vision
                        if (Vector3.Angle(targetDir, transform.forward) <= coneOfVision * .5f)
                        {
                            CheckGuardState(guards[i]);
                        }
                    }

                    else
                    {
                        continue;
                    }
                }

                // this is the equivalent of calling Set() on the first handle, and WaitOne() on the other, effectively releasing one thread, and blocking the other
                WaitHandle.SignalAndWait(mainThreadWait, childThreadWait);
            }
        }
コード例 #14
0
        public void Schedule()
        {
            _state.NeedsScheduling = false;
            Thread.MemoryBarrier();
            KThread currentThread  = KernelStatic.GetCurrentThread();
            KThread selectedThread = _state.SelectedThread;

            // If the thread is already scheduled and running on the core, we have nothing to do.
            if (currentThread == selectedThread)
            {
                return;
            }

            currentThread.SchedulerWaitEvent.Reset();
            currentThread.ThreadContext.Unlock();

            // Wake all the threads that might be waiting until this thread context is unlocked.
            for (int core = 0; core < CpuCoresCount; core++)
            {
                _context.Schedulers[core]._idleInterruptEvent.Set();
            }

            KThread nextThread = PickNextThread(selectedThread);

            if (currentThread.Context.Running)
            {
                // Wait until this thread is scheduled again, and allow the next thread to run.
                WaitHandle.SignalAndWait(nextThread.SchedulerWaitEvent, currentThread.SchedulerWaitEvent);
            }
            else
            {
                // Allow the next thread to run.
                nextThread.SchedulerWaitEvent.Set();

                // We don't need to wait since the thread is exiting, however we need to
                // make sure this thread will never call the scheduler again, since it is
                // no longer assigned to a core.
                currentThread.MakeUnschedulable();

                // Just to be sure, set the core to a invalid value.
                // This will trigger a exception if it attempts to call schedule again,
                // rather than leaving the scheduler in a invalid state.
                currentThread.CurrentCore = -1;
            }
        }
コード例 #15
0
        public void CalculateVelocities()
        {
            while (Physics.globalRunning)
            {
                for (int i = offset; i < Physics.objectIndex; i += steps)
                {
                    for (int j = 0; j < Physics.objectIndex; j++)
                    {
                        NObject obj1 = Physics.objects[i];
                        NObject obj2 = Physics.objects[j];
                        if (obj1 == obj2)
                        {
                            continue;
                        }

                        double dirx      = obj2.posx - obj1.posx;
                        double diry      = obj2.posy - obj1.posy;
                        double dirLength = Math.Sqrt(dirx * dirx + diry * diry);
                        dirx /= dirLength;
                        diry /= dirLength;

                        double forceTwo = (Physics.gravity * obj1.Mass * obj2.Mass) / (dirLength * dirLength);

                        double forx = dirx * forceTwo;
                        double fory = diry * forceTwo;
                        if (Double.IsNaN(forx))
                        {
                            forx = 0;
                        }
                        if (Double.IsNaN(fory))
                        {
                            fory = 0;
                        }
                        lock (obj1)
                        {
                            obj1.velx      += (deltaTime * forx) / obj1.Mass;
                            obj1.vely      += (deltaTime * fory) / obj1.Mass;
                            obj1.temp_posx += deltaTime * obj1.velx;
                            obj1.temp_posy += deltaTime * obj1.vely;
                        }
                    }
                }
                WaitHandle.SignalAndWait(wStatus, nStatus);
            }
        }
コード例 #16
0
        /// <summary>
        /// method called to read the next line of text received by the background
        /// reader thread from the stream.
        /// </summary>
        /// <param name="Wait"></param>
        /// <returns></returns>
        public string GetLine(int?MillisecondsTimeout = null)
        {
            string gotLine = null;

            bool gotLock = false;

            try
            {
                gotLock = this.QueuedOutputLock.WaitOne();
            }
            finally
            {
                if (gotLock == true)
                {
                    if (MillisecondsTimeout == null)
                    {
                        this.QueuedOutputLock.ReleaseMutex();
                    }
                    else
                    {
                        WaitHandle.SignalAndWait(
                            this.QueuedOutputLock, this.QueuedOutputAvailable,
                            MillisecondsTimeout.Value,
                            false);
                    }
                }
            }

            lock (OutputStream)
            {
                if (OutputLocation >= QueuedOutput.Count)
                {
                    this.QueuedOutput.Clear();
                    this.OutputLocation = 0;
                    gotLine             = null;
                }
                else
                {
                    gotLine              = this.QueuedOutput[this.OutputLocation];
                    this.OutputLocation += 1;
                }
            }

            return(gotLine);
        }
コード例 #17
0
ファイル: MessageClient.cs プロジェクト: snowdream1985/Slam
        private async Task <bool> SendMessage(string Message)
        {
            int bufferSize = Message.Length * sizeof(Char);

            byte[]       message  = new byte[bufferSize];
            UTF8Encoding encoding = new UTF8Encoding();

            encoding.GetBytes(Message, 0, Message.Length, message, 0);

            using (var viewStream = _mmf.CreateViewStream())
            {
                viewStream.Position = 0;
                viewStream.Write(message, 0, bufferSize);
                WaitHandle.SignalAndWait(_messageWait, _messageHandled);
            }

            return(true);
        }
コード例 #18
0
    public static void Main()
    {
        // Create an AutoReset EventWaitHandle
        //
        ewh = new EventWaitHandle(false, EventResetMode.AutoReset);


        for (int i = 0; i <= 4; i++)
        {
            Thread t = new Thread(
                new ParameterizedThreadStart(ThreadProc)
                );
            t.Start(i);
        }

        // Wait until all the threads have started and blocked.
        // When multiple threads use a 64-bit value on a 32-bit
        // system, you must access the value through the
        // Interlocked class to guarantee thread safety.
        //
        while (Interlocked.Read(ref threadCount) < 5)
        {
            Thread.Sleep(500);
        }

        // Release one thread each time the user presses ENTER,
        // until all threads have been released.
        //
        while (Interlocked.Read(ref threadCount) > 0)
        {
            Console.WriteLine("Press ENTER to release a waiting thread.");
            Console.ReadLine();

            // SignalAndWait signals the EventWaitHandle, which
            // releases exactly one thread before resetting,
            // because it was created with AutoReset mode.
            // SignalAndWait then blocks on clearCount, to
            // allow the signaled thread to decrement the count
            // before looping again.
            //
            WaitHandle.SignalAndWait(ewh, clearCount);
        }
        Console.WriteLine();
    }
コード例 #19
0
ファイル: signalwait2.cs プロジェクト: sahilagnihotri/Chess
        public static bool Run()
        {
            a = new AutoResetEvent(false);
            b = new AutoResetEvent(false);
            Thread t = new Thread(delegate()
            {
                WaitHandle.SignalAndWait(a, b);
            });

            t.Start();
            // put parent thread code here
            b.Set();
            a.WaitOne();
            bool ret = b.WaitOne(0, false);

            t.Join();
            // check consistency of state
            return(ret == false);
        }
コード例 #20
0
ファイル: Debugger.cs プロジェクト: laszlo-kiss/Dataphor
        /// <summary>
        /// Yields the current program to the debugger if a breakpoint or break condition is satisfied.
        /// </summary>
        public void Yield(ServerProcess process, PlanNode node)
        {
            if (!process.IsLoading())
            {
                try
                {
                    Monitor.Enter(_syncHandle);
                    try
                    {
                        if (ShouldBreak(process, node))
                        {
                            _brokenProcesses.Add(process);
                            InternalPause();
                        }

                        while (_isPauseRequested && _processes.Contains(process))
                        {
                            _pausedCount++;
                            Monitor.Exit(_syncHandle);
                            try
                            {
                                                                #if !SILVERLIGHT
                                WaitHandle.SignalAndWait(_waitSignal, _pauseSignal);
                                                                #endif
                            }
                            finally
                            {
                                Monitor.Enter(_syncHandle);
                                _pausedCount--;
                            }
                        }
                    }
                    finally
                    {
                        Monitor.Exit(_syncHandle);
                    }
                }
                catch
                {
                    // Do nothing, no error should ever be thrown from here
                }
            }
        }
コード例 #21
0
 public static void Main()
 {
     for (int i = 0; i <= 4; i++)
     {
         Thread t = new Thread(new ParameterizedThreadStart(ThreadProc));
         t.Start(i);
     }
     while (Interlocked.Read(ref _threadCount) < 5) //wait until all threads are blocked.
     {
         Thread.Sleep(500);
     }
     while (Interlocked.Read(ref _threadCount) > 0)
     {
         Console.WriteLine("Press ENTER to release a waiting thread.");
         Console.ReadLine();
         WaitHandle.SignalAndWait(Ewh, ClearCount); //signals ewh and waits for signal on clearCount.
     }
     Ewh.Set();
 }
コード例 #22
0
        public void StopExploding()
        {
            WaitHandle.SignalAndWait(explodeEvents[(int)ExplodeEvents.Stop], explodeEvents[(int)ExplodeEvents.NotRunning]);
            explodeEvents[(int)ExplodeEvents.Stop].Reset();
            int numReqs   = outstandingRequests.Count;
            int doneSoFar = 0;

            WaitHandle[] reqHandles = outstandingRequests.ToArray();
            WaitHandle[] part       = new WaitHandle[63];
            while (numReqs > 0)
            {
                int toCopy = Math.Min(numReqs, 63);
                outstandingRequests.CopyTo(doneSoFar, part, 0, toCopy);
                numReqs   -= toCopy;
                doneSoFar += toCopy;
                WaitHandle.WaitAll(part);
            }
            outstandingRequests.Clear();
        }
コード例 #23
0
        protected override void BeforeRenderFrame()
        {
            WaitForRenderer = false;

            if (Closing)
            {
                return;
            }

            if (IsMultiThreaded)
            {
                if (RenderFrameNumber == 0)
                {
                    RenderWaiter.WaitOne();
                }
                else
                {
                    WaitHandle.SignalAndWait(TestWaiter, RenderWaiter);
                }
            }
        }
コード例 #24
0
 public override void Start()
 {
     base.Start();
     while (IsRunning)
     {
         try
         {
             Logger.LogInformation("开始运行任务:{0}", ToString());
             OnRunning();
             Logger.LogInformation("结束运行任务:{0}", ToString());
         }
         catch (Exception ex)
         {
             Logger.LogError(ex, ToString());
         }
         finally
         {
             WaitHandle.SignalAndWait(_toSignal, _toWaitOn, _interval, false);
         }
     }
 }
コード例 #25
0
        /// <summary>
        /// 获取一个缓存对象,当缓存用尽时,将根据OperateAtExhaust处理
        /// </summary>
        /// <returns></returns>
        public T GetInstance()
        {
            T Result = null;

            #region 获取对象

            EventSync.WaitOne();

            if (IdleCount < 0)
            {
                if (OperateAtExhaust.Equals(EnumOperateAtExhaust.CreateNew))
                {
                    Result = new T();
                }
            }
            else
            {
                if (object.ReferenceEquals(null, Cache[--IdleCount]))
                {
                    Cache[IdleCount] = new T();
                }
                Result = Cache[IdleCount];
            }

            #endregion

            if (object.ReferenceEquals(null, Result) && OperateAtExhaust.Equals(EnumOperateAtExhaust.Suspend))
            {
                //缓存用尽时阻塞线程,等待其它线程释放对象
                WaitHandle.SignalAndWait(EventSync, EventObjRelease);
                return(GetInstance());
            }
            else
            {
                EventSync.Set();
                return(Result);
            }

            return(null);
        }
コード例 #26
0
    void ThreadLoop()
    {
        // Resets wait signal
        flockWait.Reset();
        // Waits for signal to continue running
        flockWait.WaitOne();

        while (running)
        {
            // Resets wait signal
            flockWait.Reset();

            // Loops through and calculates boid rules
            foreach (var b in boidScripts)
            {
                b.BoidFunc(flockInfo);
            }

            // Signals mainthread that we are done, and waits for new signal
            WaitHandle.SignalAndWait(mainWait, flockWait);
        }
    }
コード例 #27
0
            /// <summary>
            /// Unlocks the resource specified by the caller. Does nothing in case the resource is not already locked. If
            /// the token is not registered or resource is null, the method returns a special value. It is possible
            /// for the task to finish execution while calling this method, in which case another special value is returned.
            /// </summary>
            /// <param name="resource">Resource to be unlocked, should be non null.</param>
            /// <returns>1 In case the task completed while waiting to unlock the resource. 0 in case the unlocking has
            ///         been successful, or if a task was not locking this resource and -1 in case
            ///         the token is not registered, or a resource is null.</returns>
            public int UnlockResource(Object resource)
            {
                if (!isRegistered || resource == null)
                {
                    return(-1);
                }
                EventWaitHandle waitingOnResponse = new EventWaitHandle(false, EventResetMode.AutoReset);

                this.waitingOnResponse = waitingOnResponse;
                Scheduler.eventQueue.Add(new TaskWantsToUnlockResourceEvent(Scheduler, this, waitingOnResponse, resource));
                if (IsCanceled)
                {
                    return(1);
                }
                if (IsPaused)
                {
                    WaitHandle.SignalAndWait(TaskPaused, TaskContinued);
                }

                waitingOnResponse.WaitOne();
                return(0);
            }
コード例 #28
0
        public static void Exec(Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            if (Instance == null)
            {
                throw new NullReferenceException("MainThread was not initialized.");
            }

            if (Instance.UnityMainThread == Thread.CurrentThread)
            {
                throw new RedundancyException("You are calling the main thread from itself.");
            }

            action += () => { Instance.syncWaitHandle.Set(); };

            Instance.ActionQueue.Add(action);
            WaitHandle.SignalAndWait(Instance.mainWaitHandle, Instance.syncWaitHandle);
        }
コード例 #29
0
        private void IdleThreadLoop()
        {
            while (_context.Running)
            {
                _state.NeedsScheduling = false;
                Thread.MemoryBarrier();
                KThread nextThread = PickNextThread(_state.SelectedThread);

                if (_idleThread != nextThread)
                {
                    _idleThread.SchedulerWaitEvent.Reset();
                    WaitHandle.SignalAndWait(nextThread.SchedulerWaitEvent, _idleThread.SchedulerWaitEvent);
                }

                _idleInterruptEvent.WaitOne();
            }

            lock (_idleInterruptEventLock)
            {
                _idleInterruptEvent.Dispose();
                _idleInterruptEvent = null;
            }
        }
コード例 #30
0
        public static void SignalAndWait_InvalidArgs()
        {
            var toSignal = new ManualResetEvent(false);
            var toWaitOn = new ManualResetEvent(true);

            Assert.Throws <ArgumentNullException>(() => WaitHandle.SignalAndWait(null, toWaitOn));
            Assert.False(toSignal.WaitOne(0));
            Assert.Throws <ArgumentNullException>(() => WaitHandle.SignalAndWait(toSignal, null));
            Assert.False(toSignal.WaitOne(0));

            Assert.Throws <ArgumentOutOfRangeException>(() => WaitHandle.SignalAndWait(toSignal, toWaitOn, -2, false));
            Assert.False(toSignal.WaitOne(0));
            Assert.True(WaitHandle.SignalAndWait(toSignal, toWaitOn, -1, false));
            Assert.True(toSignal.WaitOne(0));
            toSignal.Reset();

            var invalidWh = new TestWaitHandle();

            Assert.Throws <ObjectDisposedException>(() => WaitHandle.SignalAndWait(invalidWh, toWaitOn));
            Assert.False(toSignal.WaitOne(0));
            Assert.Throws <ObjectDisposedException>(() => WaitHandle.SignalAndWait(toSignal, invalidWh));
            Assert.False(toSignal.WaitOne(0));
        }