Ejemplo n.º 1
0
        private static RegisteredWaitHandle RegisterWaitForSingleObject(  // throws RegisterWaitException
            WaitHandle waitObject,
            WaitOrTimerCallback callBack,
            object?state,
            uint millisecondsTimeOutInterval,
            bool executeOnlyOnce,    // NOTE: we do not allow other options that allow the callback to be queued as an APC
            bool compressStack
            )
        {
            RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle();

            if (callBack != null)
            {
                _ThreadPoolWaitOrTimerCallback callBackHelper = new _ThreadPoolWaitOrTimerCallback(callBack, state, compressStack);
                state = (object)callBackHelper;
                // call SetWaitObject before native call so that waitObject won't be closed before threadpoolmgr registration
                // this could occur if callback were to fire before SetWaitObject does its addref
                registeredWaitHandle.SetWaitObject(waitObject);
                IntPtr nativeRegisteredWaitHandle = RegisterWaitForSingleObjectNative(waitObject,
                                                                                      state,
                                                                                      millisecondsTimeOutInterval,
                                                                                      executeOnlyOnce,
                                                                                      registeredWaitHandle);
                registeredWaitHandle.SetHandle(nativeRegisteredWaitHandle);
            }
            else
            {
                throw new ArgumentNullException(nameof(WaitOrTimerCallback));
            }
            return(registeredWaitHandle);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Inicia o serviço de monitor de lucro prejuízo chamando o método StartMonitor
        /// Esse é um método padrão da Gradual.OMS.Library e é acionado sempre que o
        /// serviço inicializa
        /// </summary>
        public void IniciarServico()
        {
            try
            {
                logger.Info("Iniciando o servico de Monitoramento de Compliance");

                logger.Info("Inicia Thread responsavel por armazenar o monitor em memoria.");

                ThreadResetLoadSuitability = new WaitOrTimerCallback(StartLoadSuitability);

                ThreadPool.RegisterWaitForSingleObject(lThreadEvent, ThreadResetLoadSuitability, null, this.TemporizadorIntervaloVerificacao, false);

                //ThreadResetPosicao = new WaitOrTimerCallback(StartMonitorComplianceEvent);

                //ThreadPool.RegisterWaitForSingleObject(lThreadEvent, ThreadResetPosicao, null, this.TemporizadorIntervaloVerificacao, false);

                ThreadResetLoadChurning = new WaitOrTimerCallback(StartLoadComplianceChurning);

                ThreadPool.RegisterWaitForSingleObject(lThreadEvent, ThreadResetLoadChurning, null, this.TemporizadorIntervaloVerificacao, false);

                //ThreadPool.QueueUserWorkItem(new WaitCallback(CarregarMonitoresMemoria), null);

                thThreadCarregarMonitorMemoria      = new Thread(new ThreadStart(ThreadCarregarMonitorMemoria));
                thThreadCarregarMonitorMemoria.Name = "ThreadCarregarMonitorMemoria";
                thThreadCarregarMonitorMemoria.Start();

                _ServicoStatus = ServicoStatus.EmExecucao;

                logger.Info("Processo inicializado com sucesso.");
            }
            catch (Exception ex)
            {
                logger.Error("Ocorreu um erro ao Iniciar o Servico de Compliance.", ex);
            }
        }
Ejemplo n.º 3
0
        private static RegisteredWaitHandle RegisterWaitForSingleObject(  // throws RegisterWaitException
            WaitHandle waitObject,
            WaitOrTimerCallback callBack,
            Object state,
            uint millisecondsTimeOutInterval,
            bool executeOnlyOnce,                                  // NOTE: we do not allow other options that allow the callback to be queued as an APC
            ref StackCrawlMark stackMark,
            bool compressStack
            )
        {
            if (RemotingServices.IsTransparentProxy(waitObject))
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy"));
            }
            RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle();
            IntPtr nativeRegisteredWaitHandle         = RegisterWaitForSingleObjectNative(waitObject,
                                                                                          callBack,
                                                                                          state,
                                                                                          millisecondsTimeOutInterval,
                                                                                          executeOnlyOnce,
                                                                                          registeredWaitHandle,
                                                                                          ref stackMark,
                                                                                          compressStack);

            registeredWaitHandle.SetHandle(nativeRegisteredWaitHandle);
            return(registeredWaitHandle);
        }
Ejemplo n.º 4
0
        public IRegisteredCallback Create(WaitOrTimerCallback callback, object state)
        {
            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            AutoResetEvent waitEvent = null;

            try
            {
                waitEvent = new AutoResetEvent(false);
                RegisteredWaitHandle waitHandle = null;

                try
                {
                    waitHandle = ThreadPool.RegisterWaitForSingleObject(waitEvent, callback, state, Timeout.Infinite, false);

                    return(new RegisteredCallback(
                               waitEvent,
                               waitHandle));
                }
                catch (Exception)
                {
                    waitHandle?.Unregister(waitEvent);
                    throw;
                }
            }
            catch (Exception)
            {
                waitEvent?.Dispose();
                throw;
            }
        }
 public SafeTimer()
 {
     WaitFlag = false;
     timeout  = 0;
     WOTcb    = new WaitOrTimerCallback(HandleTimer);
     OpenSource.Utilities.InstanceTracker.Add(this);
 }
Ejemplo n.º 6
0
        static void Main()
        {
            AutoResetEvent      auto     = new AutoResetEvent(false);
            WaitOrTimerCallback callback = new WaitOrTimerCallback(CallbackMethod);

            // auto - от кого ждать сингнал
            // callback - что выполнять
            // null - 1-й аргумент Callback метода
            // 1000 - интервал между вызовами Callback метода
            // если true - вызвать Callback метод один раз. Если false - вызывать Callback метод с интервалом.
            //      ThreadPool.RegisterWaitForSingleObject(auto, callback, null, Timeout.Infinite, true);

            var waitHandle = ThreadPool.RegisterWaitForSingleObject(auto, callback, null, 1000, false);

            Console.WriteLine("S - сигнал, Q - выход");

            while (true)
            {
                string operation = Console.ReadKey(true).KeyChar.ToString().ToUpper();

                if (operation == "S")
                {
                    auto.Set();
                }
                if (operation == "Q")
                {
                    waitHandle.Unregister(auto);
                    break;
                }
            }
            Console.ReadKey();
        }
Ejemplo n.º 7
0
            public static Task <bool> WaitForProcessExitAsync(uint pid)
            {
                void *hProcess = OpenProcess(SYNCHRONIZE, 0, pid);

                if (hProcess == null)
                {
                    return(Task.FromResult(false));
                }

                var tasker = new TaskCompletionSource <bool>();

                var hProcessSafe = new NativeWaitHandle(hProcess, true);
                RegisteredWaitHandle registered = null;
                WaitOrTimerCallback  λHappened  = (state, timeout) =>
                {
                    hProcessSafe.Close();
#pragma warning disable once AccessToModifiedClosure
                    registered?.Unregister(null);
                    tasker.SetResult(true);
                };

                registered = ThreadPool.RegisterWaitForSingleObject(hProcessSafe, λHappened, Missing.Value, -1, true);

                return(tasker.Task);
            }
Ejemplo n.º 8
0
        public OverlappedContext()
        {
            if (OverlappedContext.completeCallback == null)
            {
                OverlappedContext.completeCallback = Fx.ThunkCallback(new IOCompletionCallback(CompleteCallback));
            }
            if (OverlappedContext.eventCallback == null)
            {
                OverlappedContext.eventCallback = Fx.ThunkCallback(new WaitOrTimerCallback(EventCallback));
            }
            if (OverlappedContext.cleanupCallback == null)
            {
                OverlappedContext.cleanupCallback = Fx.ThunkCallback(new WaitOrTimerCallback(CleanupCallback));
            }

            this.bufferHolder     = new object[] { OverlappedContext.dummyBuffer };
            this.overlapped       = new Overlapped();
            this.nativeOverlapped = this.overlapped.UnsafePack(OverlappedContext.completeCallback, this.bufferHolder);

            // When replacing the buffer, we need to provoke the CLR to fix up the handle of the pin.
            this.pinnedHandle = GCHandle.FromIntPtr(*((IntPtr *)nativeOverlapped +
                                                      (IntPtr.Size == 4 ? HandleOffsetFromOverlapped32 : HandleOffsetFromOverlapped64)));
            this.pinnedTarget = this.pinnedHandle.Target;

            // Create the permanently rooted holder and put it in the Overlapped.
            this.rootedHolder           = new RootedHolder();
            this.overlapped.AsyncResult = rootedHolder;
        }
Ejemplo n.º 9
0
		internal RegisteredWaitHandle (WaitHandle waitObject, WaitOrTimerCallback callback, 
												 object cbState, int timeout, bool executeOnlyOnce)
		{
			this.waitObject = waitObject;
			this.callback = callback;
			this.cbState = cbState;
			this.timeout = timeout;
         this.executeOnlyOnce = executeOnlyOnce;

			StWaitable waitable;
			if ((waitable = waitObject.waitable) == null) {

				/*
				 * Either we're dealing with a disposed wait handle
				 * or with some other derived class.
				 */
 
				UnparkCallback (StParkStatus.Inflated);
				return;
			}

			cbparker = new CbParker (UnparkCallback, false, true);
			int ignored = 0;
         waitBlock = waitable._WaitAnyPrologue (cbparker, StParkStatus.Success, ref hint, ref ignored);

			state = ACTIVE;
         int ws = cbparker.EnableCallback (timeout);
         if (ws != StParkStatus.Pending) {
				UnparkCallback (ws);
	      }
		}
Ejemplo n.º 10
0
        public void StartImportacaoClienteFinancial(object state)
        {
            try
            {
                gLogger.Info("StartImportacaoClientePosicao - Iniciando Serviço de Aplicacao e Resgate");

                ThreadResetFinancial = new WaitOrTimerCallback(ThreadImportacaoCliente);

                ThreadPool.RegisterWaitForSingleObject(lThreadEvent, ThreadResetFinancial, null, this.IntervaloImportacaoCliente, false);

                //thThreadImportacaoCliente = new Thread(new ThreadStart(ThreadImportacaoCliente));
                //thThreadImportacaoCliente.Name = "ThreadAplicacaoResgate";
                //thThreadImportacaoCliente.Start();

                //thThreadImportacaoPosicao = new Thread(new ThreadStart(ThreadImportacaoPosicao));
                //thThreadImportacaoPosicao.Name = "ThreadImportacaoPosicao";
                //thThreadImportacaoPosicao.Start();

                //thThreadImportacaoCarteira = new Thread(new ThreadStart(ThreadImportacaoCarteiraPosicao));
                //thThreadImportacaoCarteira.Name = "ThreadImportacaoCarteira";
                //thThreadImportacaoCarteira.Start();

                gLogger.Info("*****************************************************************");
                gLogger.Info("***********Processo de inicialização finalizado******************");
                gLogger.Info("*****************************************************************");
            }
            catch (Exception ex)
            {
                gLogger.Error("Ocorreu um erro ao acessar o metodo StartImportacaoClientePosicao.", ex);
            }
        }
Ejemplo n.º 11
0
        public IAsyncResult BeginAsync(AsyncCallback callback, object state)
        {
            if (_waitHandle != null)
            {
                throw new InvalidOperationException("The asynchronous request was already started.");
            }

            _state = state;
            lock (_completionCallbacks)
                _completionCallbacks.Add(callback);

            WaitOrTimerCallback timerCallback = (s, timeoutExpired) =>
            {
                if (timeoutExpired)
                {
                    lock (_completionCallbacks)
                    {
                        if (_timeoutHandler != null)
                        {
                            _completionCallbacks.Add(asyncResult => _timeoutHandler.HandleTimeout(_message));
                        }
                        else
                        {
                            _exception = new RequestTimeoutException(_requestId);
                        }
                    }

                    NotifyComplete();
                }
            };

            _waitHandle = ThreadPool.RegisterWaitForSingleObject(CompleteEvent, timerCallback, state, _timeout, true);

            return(this);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Execute an action on the thread pool after a specified number of milliseconds.
        /// </summary>
        /// <param name="action">The action to be executed.</param>
        /// <param name="delay">The amount of time to wait before execution, in milliseconds.</param>
        /// <returns>A cancellation token that can be used to cancel the operation.</returns>
        public static ICancellationToken DelayAndExecute(this Action action, int delay)
        {
            object                 waitHandleLock    = new object();
            ManualResetEvent       waitObj           = new ManualResetEvent(false);
            DelayCancellationToken cancellationToken = new DelayCancellationToken(waitObj);
            RegisteredWaitHandle   waitHandle        = null;

            WaitOrTimerCallback callback = (state, timeout) =>
            {
                if (Interlocked.Exchange(ref waitHandleLock, null) == null)
                {
                    waitHandle.Unregister(null);
                    cancellationToken.Dispose();
                }

                if (!timeout)
                {
                    return;
                }

                action();
            };

            waitHandle = ThreadPool.RegisterWaitForSingleObject(waitObj, callback, null, delay, true);

            if (Interlocked.Exchange(ref waitHandleLock, null) == null)
            {
                waitHandle.Unregister(null);
                cancellationToken.Dispose();
            }

            return(cancellationToken);
        }
Ejemplo n.º 13
0
        public static void Run(ISingleInstanceApp app, string[] args = null)
        {
            var mutex       = new Mutex(true, $"SingleInstance_Mutex_{app.Id}");
            var eventHandle = new EventWaitHandle(false, EventResetMode.AutoReset, $"SingleInstance_StartEvent_{app.Id}");

            try
            {
                if (mutex.WaitOne(TimeSpan.Zero, true))
                {
                    var scheduler = SynchronizationContext.Current == null ? TaskScheduler.Current : TaskScheduler.FromCurrentSynchronizationContext();
                    WaitOrTimerCallback callback = delegate
                    {
                        Task.Factory.StartNew(() => app.Activate(), CancellationToken.None, TaskCreationOptions.None, scheduler);
                    };

                    var registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(eventHandle, callback, null, Timeout.Infinite, false);

                    app.Run(args);

                    mutex.ReleaseMutex();
                    registeredWaitHandle.Unregister(null);
                }
                else
                {
                    eventHandle.Set();
                }
            }
            finally
            {
                eventHandle.Close();
                eventHandle.Dispose();
                mutex.Close();
                mutex.Dispose();
            }
        }
Ejemplo n.º 14
0
        public IAsyncResult BeginSend(AsyncCallback callback, object state)
        {
            _state = state;

            UnsubscribeAction unsubscribeToken = () => true;

            unsubscribeToken = SubscribeToResponseMessages(unsubscribeToken);

            WaitOrTimerCallback timerCallback = (s, timedOut) =>
            {
                unsubscribeToken();

                if (timedOut)
                {
                    if (_timeoutAction != null)
                    {
                        _timeoutAction();
                    }
                }

                callback(this);
            };

            _waitHandle = ThreadPool.RegisterWaitForSingleObject(_responseReceived, timerCallback, state, _responseTimeout, true);

            InvokeRequestAction();

            return(this);
        }
Ejemplo n.º 15
0
 public SafeTimer()
 {
     WaitFlag = false;
     timeout  = 0;
     WOTcb    = HandleTimer;
     InstanceTracker.Add(this);
 }
Ejemplo n.º 16
0
        private static RegisteredWaitHandle RegisterWaitForSingleObject(
            WaitHandle waitObject,
            WaitOrTimerCallback callBack,
            Object state,
            uint millisecondsTimeOutInterval,
            bool executeOnlyOnce,
            bool flowExecutionContext)
        {
            //
            // This is just a quick-and-dirty implementation to make TaskFactory.FromAsync
            // work for the few apps that are using it.  A proper implementation would coalesce
            // multiple waits onto a single thread, so that fewer machine resources would be
            // consumed.
            //

            Debug.Assert(executeOnlyOnce);

            QueueUserWorkItem(_ =>
            {
                bool timedOut = waitObject.WaitOne((int)millisecondsTimeOutInterval);
                callBack(state, timedOut);
            });

            return(new RegisteredWaitHandle());
        }
Ejemplo n.º 17
0
        public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject,
                                                                       WaitOrTimerCallback callBack,
                                                                       object state,
                                                                       long millisecondsTimeOutInterval,
                                                                       bool executeOnlyOnce)
        {
            if (waitObject == null)
            {
                throw new ArgumentNullException("waitObject");
            }

            if (callBack == null)
            {
                throw new ArgumentNullException("callBack");
            }

            if (millisecondsTimeOutInterval < -1)
            {
                throw new ArgumentOutOfRangeException("timeout", "timeout < -1");
            }

            if (millisecondsTimeOutInterval > Int32.MaxValue)
            {
                throw new NotSupportedException("Timeout is too big. Maximum is Int32.MaxValue");
            }

            TimeSpan timeout = new TimeSpan(0, 0, 0, 0, (int)millisecondsTimeOutInterval);

            RegisteredWaitHandle waiter = new RegisteredWaitHandle(waitObject, callBack, state,
                                                                   timeout, executeOnlyOnce);

            QueueUserWorkItem(new WaitCallback(waiter.Wait), null);
            return(waiter);
        }
        public OverlappedContext()
        {
            if (OverlappedContext.completeCallback == null)
            {
                OverlappedContext.completeCallback = Fx.ThunkCallback(new IOCompletionCallback(CompleteCallback));
            }
            if (OverlappedContext.eventCallback == null)
            {
                OverlappedContext.eventCallback = Fx.ThunkCallback(new WaitOrTimerCallback(EventCallback));
            }
            if (OverlappedContext.cleanupCallback == null)
            {
                OverlappedContext.cleanupCallback = Fx.ThunkCallback(new WaitOrTimerCallback(CleanupCallback));
            }

            this.bufferHolder = new object[] { OverlappedContext.dummyBuffer };
            this.overlapped = new Overlapped();
            this.nativeOverlapped = this.overlapped.UnsafePack(OverlappedContext.completeCallback, this.bufferHolder);

            // When replacing the buffer, we need to provoke the CLR to fix up the handle of the pin.
            this.pinnedHandle = GCHandle.FromIntPtr(*((IntPtr*)nativeOverlapped +
                (IntPtr.Size == 4 ? HandleOffsetFromOverlapped32 : HandleOffsetFromOverlapped64)));
            this.pinnedTarget = this.pinnedHandle.Target;

            // Create the permanently rooted holder and put it in the Overlapped.
            this.rootedHolder = new RootedHolder();
            this.overlapped.AsyncResult = rootedHolder;
        }
Ejemplo n.º 19
0
        public IAsyncResult BeginAsync(AsyncCallback callback, object state)
        {
            if (_waitHandle != null)
            {
                throw new InvalidOperationException("The asynchronous request was already started.");
            }

            _state = state;
            lock (_completionCallbacks)
                _completionCallbacks.Add(callback);

            WaitOrTimerCallback timerCallback = (s, timeoutExpired) =>
            {
                if (timeoutExpired)
                {
                    lock (_completionCallbacks)
                        _completionCallbacks.Add(asyncResult => _timeoutCallback());

                    Fail(RequestTimeoutException.FromCorrelationId(_requestId));
                }
            };

            _waitHandle = ThreadPool.RegisterWaitForSingleObject(CompleteEvent, timerCallback, state, _timeout, true);

            return(this);
        }
 public SafeTimer()
 {
     WaitFlag = false;
     timeout = 0;
     WOTcb = new WaitOrTimerCallback(HandleTimer);
     OpenSource.Utilities.InstanceTracker.Add(this);
 }
Ejemplo n.º 21
0
        private static RegisteredWaitHandle RegisterWaitForSingleObject(
            WaitHandle waitObject,
            WaitOrTimerCallback callBack,
            object?state,
            uint millisecondsTimeOutInterval,
            bool executeOnlyOnce,
            bool flowExecutionContext)
        {
            if (waitObject == null)
            {
                throw new ArgumentNullException(nameof(waitObject));
            }

            if (callBack == null)
            {
                throw new ArgumentNullException(nameof(callBack));
            }

            RegisteredWaitHandle registeredHandle = new RegisteredWaitHandle(
                waitObject,
                new _ThreadPoolWaitOrTimerCallback(callBack, state, flowExecutionContext),
                (int)millisecondsTimeOutInterval,
                !executeOnlyOnce);

            PortableThreadPool.ThreadPoolInstance.RegisterWaitHandle(registeredHandle);
            return(registeredHandle);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Execute an action on the thread pool after a specified number of milliseconds.
        /// </summary>
        /// <param name="action">The action to be executed.</param>
        /// <param name="waitObj">The wait handle to be used to cancel execution.</param>
        /// <param name="delay">The amount of time to wait before execution, in milliseconds.</param>
        public static void DelayAndExecute(this Action action, WaitHandle waitObj, int delay)
        {
            object waitHandleLock           = new object();
            RegisteredWaitHandle waitHandle = null;

            WaitOrTimerCallback callback = (state, timeout) =>
            {
                if (Interlocked.Exchange(ref waitHandleLock, null) == null)
                {
                    waitHandle.Unregister(null);
                }

                if (!timeout)
                {
                    return;
                }

                action();
            };

            waitHandle = ThreadPool.RegisterWaitForSingleObject(waitObj, callback, null, delay, true);

            if (Interlocked.Exchange(ref waitHandleLock, null) == null)
            {
                waitHandle.Unregister(null);
            }
        }
Ejemplo n.º 23
0
 public Server()
 {
     m_CurrentConnectionCount = 0;
     m_FreeConnectionIds      = new ConcurrentQueue <int>();
     m_ConnectionList         = new List <Connection>(16);
     m_OnRecycleReady         = new WaitOrTimerCallback(RecycleConnection);
 }
        // We need this to make the use of the property as an attribute
        // light-weight. This allows us to delay initialize everything we
        // need to fully function as a ContextProperty.
        internal virtual void InitIfNecessary()
        {
            lock (this)
            {
                if (_asyncWorkEvent == null)
                {
                    // initialize thread pool event to non-signaled state.
                    _asyncWorkEvent = new AutoResetEvent(false);

                    _workItemQueue = new Queue();
                    _asyncLcidList = new ArrayList();

                    WaitOrTimerCallback callBackDelegate =
                        new WaitOrTimerCallback(this.DispatcherCallBack);

                    // Register a callback to be executed by the thread-pool
                    // each time the event is signaled.
                    _waitHandle = ThreadPool.RegisterWaitForSingleObject(
                        _asyncWorkEvent,
                        callBackDelegate,
                        null,             // state info
                        _timeOut,
                        false);           // bExecuteOnlyOnce
                }
            }
        }
Ejemplo n.º 25
0
 public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject
     (WaitHandle waitObject, WaitOrTimerCallback callBack,
     Object state, TimeSpan timeout,
     bool executeOnlyOnce)
 {
     return(RegisterWaitForSingleObject
                (waitObject, callBack, state,
                Monitor.TimeSpanToMS(timeout), executeOnlyOnce));
 }
 internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, object state, bool compressStack, ref StackCrawlMark stackMark)
 {
     this._waitOrTimerCallback = waitOrTimerCallback;
     this._state = state;
     if (compressStack && !ExecutionContext.IsFlowSuppressed())
     {
         this._executionContext = ExecutionContext.Capture(ref stackMark, ExecutionContext.CaptureOptions.OptimizeDefaultCase | ExecutionContext.CaptureOptions.IgnoreSyncCtx);
     }
 }
Ejemplo n.º 27
0
 internal RegisteredWaitHandle(WaitHandle waitObject, WaitOrTimerCallback callback, object state, TimeSpan timeout, bool executeOnlyOnce)
 {
     _waitObject      = waitObject;
     _callback        = callback;
     _state           = state;
     _timeout         = timeout;
     _executeOnlyOnce = executeOnlyOnce;
     _cancelEvent     = new ManualResetEvent(false);
 }
Ejemplo n.º 28
0
 public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject,
                                                                WaitOrTimerCallback callBack,
                                                                object state,
                                                                TimeSpan timeout,
                                                                bool executeOnlyOnce)
 {
     return(RegisterWaitForSingleObject(waitObject, callBack, state,
                                        (long)timeout.TotalMilliseconds, executeOnlyOnce));
 }
Ejemplo n.º 29
0
 public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject,
                                                                WaitOrTimerCallback callBack,
                                                                object state,
                                                                uint millisecondsTimeOutInterval,
                                                                bool executeOnlyOnce)
 {
     return(RegisterWaitForSingleObject(waitObject, callBack, state,
                                        (long)millisecondsTimeOutInterval, executeOnlyOnce));
 }
Ejemplo n.º 30
0
            protected override void QueueTask(Task task)
            {
                Console.WriteLine("Queue Task ThreadID {0}", Thread.CurrentThread.ManagedThreadId);
                queue.Enqueue(task);

                WaitOrTimerCallback callback = (object state, bool timeout) => { base.TryExecuteTask(queue.Dequeue()); };

                ThreadPool.RegisterWaitForSingleObject(auto, callback, null, 2000, true);
            }
Ejemplo n.º 31
0
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// waitortimercallback.BeginInvoke(state, timedOut, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this WaitOrTimerCallback waitortimercallback, Object state, Boolean timedOut, AsyncCallback callback)
        {
            if (waitortimercallback == null)
            {
                throw new ArgumentNullException("waitortimercallback");
            }

            return(waitortimercallback.BeginInvoke(state, timedOut, callback, null));
        }
Ejemplo n.º 32
0
 internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, object state, bool compressStack, ref StackCrawlMark stackMark)
 {
     this._waitOrTimerCallback = waitOrTimerCallback;
     this._state = state;
     if (compressStack && !ExecutionContext.IsFlowSuppressed())
     {
         this._executionContext = ExecutionContext.Capture(ref stackMark, ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
     }
 }
Ejemplo n.º 33
0
 private static extern IntPtr RegisterWaitForSingleObjectNative(
     WaitHandle waitHandle,
     WaitOrTimerCallback callBack,
     Object state,
     long timeOutInterval,
     bool executeOnlyOnce,
     RegisteredWaitHandle registeredWaitHandle,
     ref StackCrawlMark stackMark,
     bool compressStack
     );
 internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, object state, bool compressStack, ref StackCrawlMark stackMark)
 {
     this._waitOrTimerCallback = waitOrTimerCallback;
     this._state = state;
     if (compressStack && !ExecutionContext.IsFlowSuppressed())
     {
         this._executionContext = ExecutionContext.Capture(ref stackMark);
         ExecutionContext.ClearSyncContext(this._executionContext);
     }
 }
 internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, object state, bool compressStack, ref StackCrawlMark stackMark)
 {
     this._waitOrTimerCallback = waitOrTimerCallback;
     this._state = state;
     if (compressStack && !ExecutionContext.IsFlowSuppressed())
     {
         this._executionContext = ExecutionContext.Capture(ref stackMark);
         ExecutionContext.ClearSyncContext(this._executionContext);
     }
 }
Ejemplo n.º 36
0
 private static void InitializeConnectionTimeoutHandler()
 {
     _socketTimeoutDelegate = new WaitOrTimerCallback(TimeoutConnections);
     _socketTimeoutWaitHandle = new AutoResetEvent(false);
     _registeredWaitHandle = 
         ThreadPool.UnsafeRegisterWaitForSingleObject(
             _socketTimeoutWaitHandle, 
             _socketTimeoutDelegate, 
             "IpcConnectionTimeout", 
             _socketTimeoutPollTime, 
             true); // execute only once
 } // InitializeSocketTimeoutHandler
Ejemplo n.º 37
0
		internal RegisteredWaitHandle (WaitHandle waitObject, WaitOrTimerCallback callback, object state, TimeSpan timeout, bool executeOnlyOnce)
		{
			_waitObject = waitObject;
			_callback = callback;
			_state = state;
			_timeout = timeout;
			_executeOnlyOnce = executeOnlyOnce;
			_finalEvent = null;
			_cancelEvent = new ManualResetEvent (false);
			_callsInProcess = 0;
			_unregistered = false;
		}
Ejemplo n.º 38
0
        public ConnectionCache(int keepAlive, ConnectionFactory connectionFactory)
        {
            // parameters validation
            if (connectionFactory == null)
                throw new ArgumentNullException("connectionFactory");
            if (keepAlive < 1)
                throw new ArgumentOutOfRangeException("keepAlive");

            _connectionFactory = connectionFactory;
            _keepAlive = TimeSpan.FromSeconds(keepAlive);

            // Schedule timeout method
            _timeoutDelegate = OnTimerElapsed;
            _timeoutWaitHandle = new AutoResetEvent(false);
            _registeredTimeoutWaitHandle = ThreadPool.RegisterWaitForSingleObject(
                _timeoutWaitHandle, _timeoutDelegate, null, _keepAlive, true);
        }
	/**
	 * we lay the groundwork for further async calls in page load
 	 */
	public void Page_Load( Object sender, EventArgs e )
	{
		Response.Write("page load entered\n");

		// we set the timeout to something really long, so that .net
		// won't time out our request - we want long running
		TimeSpan timeOut = new TimeSpan( 1, 0, 0, 0, 0 );
		this.AsyncTimeout = timeOut;
		
		// fire up a delegate that invokes the function that we 
		// ultimately want to call
		m_doAsyncDelegate = new DoAsyncDelegate( DoAsync );
		
		// this is a hack to get some browsers to display something
		// we write some data to fill the buffer or something	
		for( int i=0; i < 1000; i++ )
		{ 
			Response.Write("<span></span>");
		}
		Response.Flush();

		// here we set up a periodic poller using threadpool. the
		// basic idea is that we have a call back that is periodically
		// visited by a threadpool thread.  This really isn't a poll,
		// and is not really done by the threadpool, we use an autoresetevent
		m_wtCallback = new WaitOrTimerCallback( Callback );
		AutoResetEvent are = new AutoResetEvent( false );
		ThreadPool.RegisterWaitForSingleObject( are, m_wtCallback, null, 1000, false );
	
		// the meat of getting this all to work revolves around the 
		// registration of handlers for begin and end
		RegisterAsyncTask( 
			new PageAsyncTask(
	   		new BeginEventHandler( this.BeginLoad ),
	  		new EndEventHandler( this.EndLoad ),
	  		null, null, false )
		);

	}
 public unsafe OverlappedContext()
 {
     if (completeCallback == null)
     {
         completeCallback = Fx.ThunkCallback(new IOCompletionCallback(OverlappedContext.CompleteCallback));
     }
     if (eventCallback == null)
     {
         eventCallback = Fx.ThunkCallback(new WaitOrTimerCallback(OverlappedContext.EventCallback));
     }
     if (cleanupCallback == null)
     {
         cleanupCallback = Fx.ThunkCallback(new WaitOrTimerCallback(OverlappedContext.CleanupCallback));
     }
     this.bufferHolder = new object[] { dummyBuffer };
     this.overlapped = new Overlapped();
     this.nativeOverlapped = this.overlapped.UnsafePack(completeCallback, this.bufferHolder);
     this.pinnedHandle = GCHandle.FromIntPtr(*((IntPtr*) (this.nativeOverlapped + (((IntPtr.Size == 4) ? -4 : -3) * sizeof(IntPtr)))));
     this.pinnedTarget = this.pinnedHandle.Target;
     this.rootedHolder = new RootedHolder();
     this.overlapped.AsyncResult = this.rootedHolder;
 }
Ejemplo n.º 41
0
        public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object state, long millisecondsTimeOutInterval, bool executeOnlyOnce)
        {
            if (executeOnlyOnce != true)
            {
                throw new NotSupportedException("executeOnlyOnce must be true");
            }

            int tickTime = (int)Math.Min(100, millisecondsTimeOutInterval);

            int totalTimeElapsed = 0;
            Timer timer = null;

            timer = new Timer((s) =>
            {
                // Timer will fire every due period...if total time exceeds millisecondsTimeoutInterval then we call the timeoutcallback
                // otherwise we wait...if at any point the waitObject is signaled...than we can abort.
                if (waitObject.WaitOne(0))
                {
                    // Signal is set so no timeout occured
                    timer.Dispose();
                    return;
                }
                else if (totalTimeElapsed > millisecondsTimeOutInterval)
                {
                    // Timeout has occured
                    timer.Dispose();
                    callBack(state, true);
                }
                else
                {
                    totalTimeElapsed += tickTime;
                }
            }, null, tickTime, tickTime);

            return null;
        }
        internal static void AddMyObjectChanged(EventHandler<ObjectChangedEventArgs> callback,
                                        ref EventHandler<ObjectChangedEventArgs> objectChanged,
                                        object lockObjChangedEvent,
                                        ref RegisteredWaitHandle regObjChangedWaitHandle,
                                        ref AutoResetEvent objChangedEvent,
                                        ref SafeCollabEvent safeObjChangedEvent,
                                        WaitOrTimerCallback ObjectChangedCallback)
        {
            //
            // Register a wait handle if one has not been registered already
            //
            lock (lockObjChangedEvent){
                if (objectChanged == null){

                    objChangedEvent = new AutoResetEvent(false);

                    //
                    // Register callback with a wait handle
                    //

                    regObjChangedWaitHandle = ThreadPool.RegisterWaitForSingleObject(objChangedEvent, //Event that triggers the callback
                                            ObjectChangedCallback, //callback to be called 
                                            null, //state to be passed
                                            -1,   //Timeout - aplicable only for timers
                                            false //call us everytime the event is set
                                            );

                    PEER_COLLAB_EVENT_REGISTRATION pcer = new PEER_COLLAB_EVENT_REGISTRATION();
                    pcer.eventType = PeerCollabEventType.MyObjectChanged;
                    pcer.pInstance = IntPtr.Zero;


                    //
                    // Register event with collab
                    //

                    int errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterEvent(
                                                                        objChangedEvent.SafeWaitHandle,
                                                                        1,
                                                                        ref pcer,
                                                                        out safeObjChangedEvent);
                    if (errorCode != 0){
                        Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterEvent returned with errorcode {0}", errorCode);
                        throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_ObjectChangedRegFailed), errorCode);
                    }
                }
                objectChanged += callback;
            }

            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddObjectChanged() successful.");

        }
Ejemplo n.º 43
0
		public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject (WaitHandle waitObject,
			WaitOrTimerCallback callBack, object state, uint millisecondsTimeOutInterval,
			bool executeOnlyOnce) 
		{
			throw new NotImplementedException ();
		}
Ejemplo n.º 44
0
		public static RegisteredWaitHandle RegisterWaitForSingleObject (WaitHandle waitObject,
										WaitOrTimerCallback callBack,
										object state,
										uint millisecondsTimeOutInterval,
										bool executeOnlyOnce)
		{
			if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
				return Microsoft.ThreadPool.RegisterWaitForSingleObject (waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce);
			else
				return RegisterWaitForSingleObject (waitObject, callBack, state, (long) millisecondsTimeOutInterval, executeOnlyOnce);
		}
Ejemplo n.º 45
0
 public SafeTimer_SINGLE()
 {
     WOTcb = new WaitOrTimerCallback(HandleTimer);
 }
Ejemplo n.º 46
0
		void StartExitCallbackIfNeeded ()
		{
			lock (thisLock) {
				bool start = (exitWaitHandle == null && enableRaisingEvents && exited_event != null);
				if (start && process_handle != IntPtr.Zero) {
					WaitOrTimerCallback cb = new WaitOrTimerCallback (CBOnExit);
					ProcessWaitHandle h = new ProcessWaitHandle (process_handle);
					exitWaitHandle = ThreadPool.RegisterWaitForSingleObject (h, cb, this, -1, true);
				}
			}
		}
 internal virtual void InitIfNecessary()
 {
     lock (this)
     {
         if (this._asyncWorkEvent == null)
         {
             this._asyncWorkEvent = new AutoResetEvent(false);
             this._workItemQueue = new Queue();
             this._asyncLcidList = new ArrayList();
             WaitOrTimerCallback callBack = new WaitOrTimerCallback(this.DispatcherCallBack);
             this._waitHandle = ThreadPool.RegisterWaitForSingleObject(this._asyncWorkEvent, callBack, null, _timeOut, false);
         }
     }
 }
Ejemplo n.º 48
0
		public WorkItem(ClrPermissions permissions, WaitHandle waitObject,
					    WaitOrTimerCallback callback, Object state,
						int millisecondsTimeOutInterval, bool executeOnlyOnce)
				{
					this.permissions = permissions;
					this.userWorkItem = false;
					this.callback2 = callback;
					this.state = state;
					this.timeout = millisecondsTimeOutInterval;
					this.once = executeOnlyOnce;
					this.registered = true;
				}
Ejemplo n.º 49
0
	public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject
				(WaitHandle waitObject, WaitOrTimerCallback callBack,
				 Object state, uint millisecondsTimeOutInterval,
				 bool executeOnlyOnce)
			{
				return RegisterWaitForSingleObject
					(waitObject, callBack, state,
					 Timer.UIntToMS(millisecondsTimeOutInterval),
					 executeOnlyOnce);
			}
Ejemplo n.º 50
0
	public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject
				(WaitHandle waitObject, WaitOrTimerCallback callBack,
				 Object state, TimeSpan timeout,
				 bool executeOnlyOnce)
			{
				return RegisterWaitForSingleObject
					(waitObject, callBack, state,
					 Monitor.TimeSpanToMS(timeout), executeOnlyOnce);
			}
Ejemplo n.º 51
0
	// Register a callback to be invoked when a wait handle is available.
	public static RegisteredWaitHandle RegisterWaitForSingleObject
				(WaitHandle waitObject, WaitOrTimerCallback callBack,
				 Object state, int millisecondsTimeOutInterval,
				 bool executeOnlyOnce)
			{
				if(waitObject == null)
				{
					throw new ArgumentNullException("waitObject");
				}
				if(millisecondsTimeOutInterval < -1)
				{
					throw new ArgumentOutOfRangeException
						("millisecondsTimeOutInterval",
						 _("ArgRange_NonNegOrNegOne"));
				}
				WorkItem item = new WorkItem(ClrSecurity.GetPermissionsFrom(1),
											 waitObject, callBack, state,
											 millisecondsTimeOutInterval,
											 executeOnlyOnce);
				AddWorkItem(item);
				return new RegisteredWaitHandle(item);
			}
Ejemplo n.º 52
0
        private bool SetAsyncEventSelect(AsyncEventBits blockEventBits)
        {
            GlobalLog.Enter("Socket#" + ValidationHelper.HashString(this) + "::SetAsyncEventSelect", "blockEventBits:" + blockEventBits.ToString() + " m_BlockEventBits:" + m_BlockEventBits.ToString() + " willBlockInternal:" + willBlockInternal.ToString());
            GlobalLog.Assert(blockEventBits != AsyncEventBits.FdNone, "Socket#{0}::SetAsyncEventSelect|Use UnsetAsyncEventSelect for FdNone.", ValidationHelper.HashString(this));
            GlobalLog.Assert(m_BlockEventBits == AsyncEventBits.FdNone || m_BlockEventBits == blockEventBits, "Socket#{0}::SetAsyncEventSelect|Can't change from one active wait to another.", ValidationHelper.HashString(this));
            GlobalLog.Assert(m_RegisteredWait == null, "Socket#{0}::SetAsyncEventSelect|Already actively waiting on an op.", ValidationHelper.HashString(this));

            // This check is bogus, too late diggin into a historical reason for it.
            // Make sure the upper level will fail with ObjectDisposedException
            if (m_RegisteredWait != null)
                return false;

            //
            // This will put us into non-blocking mode.  Create the event if it isn't, and register a wait.
            //
            if (m_AsyncEvent == null)
            {
                Interlocked.CompareExchange<ManualResetEvent>(ref m_AsyncEvent, new ManualResetEvent(false), null);
                if (s_RegisteredWaitCallback == null)
                    s_RegisteredWaitCallback = new WaitOrTimerCallback(RegisteredWaitCallback);
            }

            //
            // Try to win over Dispose is there is a ----
            //
            if (Interlocked.CompareExchange(ref m_IntCleanedUp, 2, 0) != 0)
            {
                GlobalLog.Leave("Socket#" + ValidationHelper.HashString(this) + "::SetAsyncEventSelect() Already Cleaned up, returning ... ", string.Empty);
                return false;
            }

            try
            {
                m_BlockEventBits = blockEventBits;
                m_RegisteredWait = ThreadPool.UnsafeRegisterWaitForSingleObject(m_AsyncEvent, s_RegisteredWaitCallback, this, Timeout.Infinite, true);
            }
            finally
            {
                //
                // Release dispose if any is waiting
                //
                Interlocked.Exchange(ref m_IntCleanedUp, 0);
            }

            SocketError errorCode = SocketError.NotSocket;
            //
            // issue the native call
            //
            try {
                errorCode = UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(m_Handle, m_AsyncEvent.SafeWaitHandle, blockEventBits);
            }
            catch (Exception e)
            {
                if (NclUtilities.IsFatal(e))
                    throw;
                GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::SetAsyncEventSelect() !!! (converting to ObjectDisposed) Exception :" + e.ToString());
                GlobalLog.Assert(CleanedUp, "Socket#{0}::SetAsyncEventSelect|WSAEventSelect got exception and CleanedUp not set.", ValidationHelper.HashString(this));
            }

            if (errorCode==SocketError.SocketError) {
                //
                // update our internal state after this socket error
                // we won't throw since this is an internal method
                //
                UpdateStatusAfterSocketError(errorCode);
            }

            //
            // the call to WSAEventSelect will put us in non-blocking mode, 
            // hence we need update internal status
            //
            willBlockInternal = false;

            GlobalLog.Leave("Socket#" + ValidationHelper.HashString(this) + "::SetAsyncEventSelect", "m_BlockEventBits:" + m_BlockEventBits.ToString() + " willBlockInternal:" + willBlockInternal.ToString());
            return errorCode == SocketError.Success;
        }
Ejemplo n.º 53
0
		public static RegisteredWaitHandle RegisterWaitForSingleObject (WaitHandle waitObject,
										WaitOrTimerCallback callBack,
										object state,
										long millisecondsTimeOutInterval,
										bool executeOnlyOnce)
		{
			if (millisecondsTimeOutInterval < -1)
				throw new ArgumentOutOfRangeException ("timeout", "timeout < -1");

			if (millisecondsTimeOutInterval > Int32.MaxValue)
				throw new NotSupportedException ("Timeout is too big. Maximum is Int32.MaxValue");

			TimeSpan timeout = new TimeSpan (0, 0, 0, 0, (int) millisecondsTimeOutInterval);
			
			RegisteredWaitHandle waiter = new RegisteredWaitHandle (waitObject, callBack, state,
										timeout, executeOnlyOnce);
			QueueUserWorkItem (new WaitCallback (waiter.Wait), null);
			return waiter;
		}
Ejemplo n.º 54
0
		public static RegisteredWaitHandle RegisterWaitForSingleObject (WaitHandle waitObject,
										WaitOrTimerCallback callBack,
										object state,
										TimeSpan timeout,
										bool executeOnlyOnce)
		{
			return RegisterWaitForSingleObject (waitObject, callBack, state,
							    (long) timeout.TotalMilliseconds, executeOnlyOnce);

		}
Ejemplo n.º 55
0
        } // SocketCache


        private void InitializeSocketTimeoutHandler()
        {
            _socketTimeoutDelegate = new WaitOrTimerCallback(this.TimeoutSockets);
            _socketTimeoutWaitHandle = new AutoResetEvent(false);
            _registeredWaitHandle = 
                ThreadPool.UnsafeRegisterWaitForSingleObject(
                    _socketTimeoutWaitHandle, 
                    _socketTimeoutDelegate, 
                    "TcpChannelSocketTimeout", 
                    _socketTimeoutPollTime, 
                    true); // execute only once
        } // InitializeSocketTimeoutHandler
Ejemplo n.º 56
0
		public static RegisteredWaitHandle RegisterWaitForSingleObject (WaitHandle waitObject,
										WaitOrTimerCallback callBack,
										object state,
										uint millisecondsTimeOutInterval,
										bool executeOnlyOnce)
		{
			return RegisterWaitForSingleObject (waitObject, callBack, state,
							    (long) millisecondsTimeOutInterval, executeOnlyOnce);
		}
 // We need this to make the use of the property as an attribute 
 // light-weight. This allows us to delay initialize everything we
 // need to fully function as a ContextProperty.
 internal virtual void InitIfNecessary()
 {
     lock(this) 
     {
         if (_asyncWorkEvent == null)
         {
             // initialize thread pool event to non-signaled state.
             _asyncWorkEvent = new AutoResetEvent(false);
 
             _workItemQueue = new Queue();
             _asyncLcidList = new ArrayList();
             
             WaitOrTimerCallback callBackDelegate = 
                 new WaitOrTimerCallback(this.DispatcherCallBack);
 
             // Register a callback to be executed by the thread-pool
             // each time the event is signaled.
             _waitHandle = ThreadPool.RegisterWaitForSingleObject(
                             _asyncWorkEvent, 
                             callBackDelegate, 
                             null, // state info
                             _timeOut, 
                             false); // bExecuteOnlyOnce
         }
     }
 }
Ejemplo n.º 58
0
		public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject (WaitHandle waitObject,
			WaitOrTimerCallback callBack, object state, TimeSpan timeout,
			bool executeOnlyOnce) 
		{
			throw new NotImplementedException ();
		}
Ejemplo n.º 59
0
		void StartExitCallbackIfNeeded ()
		{
#if !NET_2_1
			bool start = (!already_waiting && enableRaisingEvents && exited_event != null);
			if (start && process_handle != IntPtr.Zero) {
				WaitOrTimerCallback cb = new WaitOrTimerCallback (CBOnExit);
				ProcessWaitHandle h = new ProcessWaitHandle (process_handle);
				ThreadPool.RegisterWaitForSingleObject (h, cb, this, -1, true);
				already_waiting = true;
			}
#endif
		}
Ejemplo n.º 60
0
		public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject (WaitHandle waitObject,
			WaitOrTimerCallback callBack, object state, uint millisecondsTimeOutInterval,
			bool executeOnlyOnce) 
		{
			if (Microsoft.ThreadPool.UseMicrosoftThreadPool)
				return Microsoft.ThreadPool.UnsafeRegisterWaitForSingleObject (waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce);
			else
				throw new NotImplementedException ();
		}