Пример #1
0
 public static void forward()
 {
     {
         Console.Write ("Hoe ver: ");
         uint cm = uint.Parse (Console.ReadLine ());
         Console.Write ("Hoe snel: ");
         SByte speed = (SByte)int.Parse (Console.ReadLine ());
         Console.WriteLine ("forward " + cm + " cm at " + speed + " % speed");
         //Convert degrees to cm. Bereken eerst de graad/Cm en vul deze in bij de conastanten.
         uint graden = (uint)(cm * graadCmForward);
         //Hier begint de magie
         waitHandle = vehicle.Forward (speed, graden, true);
         //Geef die motor even rust
         waitHandle.WaitOne ();
         string output = cm + " cm vooruit gegaan met een snelheid van " + speed + "%";
         Console.WriteLine (output);
         //Schrijf naar een bestand
         using (System.IO.StreamWriter file =
                    new System.IO.StreamWriter (@"/home/root/apps/NoWait/output.txt", true)) {
             file.WriteLine ("forward");
             file.WriteLine (cm);
             file.WriteLine (speed);
             file.WriteLine ("");
         }
         Thread.Sleep (100);
     }
 }
        /// <summary>Creates a Task that will be completed when the specified WaitHandle is signaled.</summary>
        /// <param name="factory">The target factory.</param>
        /// <param name="waitHandle">The WaitHandle.</param>
        /// <returns>The created Task.</returns>
        public static Task FromAsync(this TaskFactory factory, WaitHandle waitHandle)
        {
            if (factory == null) throw new ArgumentNullException("factory");
            if (waitHandle == null) throw new ArgumentNullException("waitHandle");

            var tcs = new TaskCompletionSource<object>();
            var rwh = ThreadPool.RegisterWaitForSingleObject(waitHandle, delegate { tcs.TrySetResult(null); }, null, -1, true);
            var t = tcs.Task;
            t.ContinueWith(_ => rwh.Unregister(null), TaskContinuationOptions.ExecuteSynchronously);
            return t;
        }
	// Unregister using a specific wait object.
	public bool Unregister(WaitHandle waitObject)
			{
				if(workItem.waitObject == waitObject)
				{
					workItem.registered = false;
					return true;
				}
				else
				{
					return false;
				}
			}
    private static void RunTest(IsolationLevel isolationLevel)
    {
        // Handles are used only to wait for both workers to complete
        var handles = new WaitHandle[] {
            new ManualResetEvent(false),
            new ManualResetEvent(false)
        };

        var options = new TransactionOptions
        {
            IsolationLevel = isolationLevel,
            Timeout = new TimeSpan(0, 0, 0, 10)
        };

        // Worker's job
        WaitCallback job = state =>
        {
            try
            {
                using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, options))
                {
                    using (var context = new NorthwindEntities())
                    {
                        var region = GetRegionById(context, 4);
                        Console.WriteLine("Updating description");
                        region.RegionDescription = region.RegionDescription.Trim() + " updated";
                        Console.WriteLine("Saving");
                        context.SaveChanges(); // Save changes to DB
                    }

                    scope.Complete(); // Commit transaction
                    Console.WriteLine("Persisted");
                }
            }
            catch (Exception e)
            {
                PrintError(e);
            }
            finally
            {
                // Signal to the main thread that the worker has completed
                ((ManualResetEvent)state).Set();
            }
        };

        // Run workers
        ThreadPool.QueueUserWorkItem(job, handles[0]);
        ThreadPool.QueueUserWorkItem(job, handles[1]);

        // Wait for both workers to complete
        WaitHandle.WaitAll(handles);
    }
Пример #5
0
 public static void forward(double cm, SByte speed, Boolean brake, Boolean silent)
 {
     //Init vehicle, waitHandle en speaker
     //Go forward with .. cm at .. speed
     LcdConsole.WriteLine ("forward " + cm + " cm at " + speed + " % speed");
     //Convert degrees to cm. Bereken eerst de graad/Cm en vul deze in bij de conastanten.
     uint graden = (uint)(cm * graadCmForward);
     //Hier begint de magie
     waitHandle = vehicle.Forward (speed, graden, brake);
     //Geef die motor even rust
     waitHandle.WaitOne ();
     LcdConsole.WriteLine ("Done moving forward!");
     if (!silent) {
         speaker.Buzz ();
     }
     Thread.Sleep (100);
 }
Пример #6
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;
        }
Пример #7
0
 protected ThreadBase(WaitHandle initEvent)
 {
     System.Threading.ThreadPool.QueueUserWorkItem(StartThread, initEvent);
 }
 public TResult GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e)
 {
     return((TResult)_workItemResult.GetResult(timeout, exitContext, cancelWaitHandle, out e));
 }
Пример #9
0
 public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object state, TimeSpan timeout, bool executeOnlyOnce)
 {
     return RegisterWaitForSingleObject(waitObject, callBack, state, (long)timeout.TotalMilliseconds, executeOnlyOnce);
 }
Пример #10
0
 public static void ExpectNoEvent(WaitHandle eventOccurred, string eventName, int timeout = WaitForUnexpectedEventTimeout)
 {
     string message = String.Format("Should not observe a {0} event within {1}ms", eventName, timeout);
     Assert.False(eventOccurred.WaitOne(timeout), message);
 }
Пример #11
0
        private bool RunTestExecutionLoop(ExecutableTestList processes, Type[] types, TestLaunchParam param)
        {
            bool bCompletedNormally = false;

            try
            {
                // Go through the list of tests...
                //for (int i = 0; i < processes.Count; i++)
                bool breakFlag = true;
                do
                {
                    breakFlag = true;
                    processes.StartExecution();
                    IEnumerator <TestInfo> curr = processes.GetUpdatableEnumerator();
                    var processNextFlag         = curr.MoveNext();
                    for (; processNextFlag;)
                    {
                        //TestInfo testInfo = processes[i];
                        var testInfo = curr.Current;
                        _currentTestInfo = testInfo;

                        /// "Stop" requested or "Halt" has not been handled at test level.
                        if (_stop)
                        {
                            System.Diagnostics.Debug.WriteLine("TEST SEQUENCE STOPPED");
                            bCompletedNormally = false;
                            break;
                        }

                        try
                        {
                            // Check if a pause should be done.
                            // If a pause should be done at this point and "Halt" is clicked
                            // during the pause = don't execute next test.
                            bool dispatcherLevelPause;
                            lock (_pauseSync)
                            {
                                dispatcherLevelPause = _dispatcherLevelPause;
                            }

                            if (dispatcherLevelPause)
                            {
                                // Sleep() returns TRUE if pause has been ended by clicking "Resume" and FALSE if "Halt"
                                // button has been clicked.
                                bool bContinue = Sleep();
                                if (!bContinue)
                                {
                                    System.Diagnostics.Debug.WriteLine("TEST SEQUENCE PAUSED");
                                    // Tests execution halted
                                    bCompletedNormally = false;
                                    break;
                                }
                            }

                            System.Diagnostics.Debug.WriteLine("TEST SEQUENCE before TestStarted");
                            // Report that a test is started
                            if (TestStarted != null)
                            {
                                TestStarted(testInfo);
                            }
                            System.Diagnostics.Debug.WriteLine("TEST SEQUENCE TestStarted");

                            _currentTest = null;
                            BaseTest test = InitCurrentTest(testInfo, types, args);
                            System.Diagnostics.Debug.WriteLine("TEST SEQUENCE InitCurrentTest");

                            // check if tests execution should be stopped
                            bool halt;
                            lock (_pauseSync)
                            {
                                halt = _delayedHalt || _stop;
                            }

                            if (halt)
                            {
                                bCompletedNormally = false;
                                System.Diagnostics.Debug.WriteLine("Handle HALT after test started");
                                break;
                            }

                            lock (_pauseSync)
                            {
                                dispatcherLevelPause = _dispatcherLevelPause;
                            }

                            if (dispatcherLevelPause)
                            {
                                // WAIT
                                bool bContinue = Sleep();
                                if (!bContinue)
                                {
                                    System.Diagnostics.Debug.WriteLine("TEST SEQUENCE PAUSED2");
                                    bCompletedNormally = false;
                                    break;
                                }
                            }

                            try
                            {
                                // start current test.
                                // (really it means that _currentTest.EntryPoint method is executed synchronously)
                                System.Diagnostics.Debug.WriteLine("TEST SEQUENCE before Start");
                                if (_currentTest == null)
                                {
                                    System.Diagnostics.Debug.WriteLine("TEST SEQUENCE Invalid Start entry point");
                                }
                                else
                                {
                                    _currentTest.Start();
                                }
                                System.Diagnostics.Debug.WriteLine("TEST SEQUENCE after Start");

                                //
                                // Feature definition process ended
                                //
                                if (testInfo.ProcessType == ProcessType.FeatureDefinition)
                                {
                                    if (test.Halted)
                                    {
                                        System.Diagnostics.Debug.WriteLine("TEST SEQUENCE HALTED");
                                        break;
                                    }
                                    else
                                    {
                                        ProfilesSupportTest pst = new ProfilesSupportTest();
                                        pst.ProfileDefinitionCompleted += pst_ProfileDefinitionCompleted;

                                        var parameters = new Dictionary <string, object>();
                                        parameters.Add("MaxPullPoints", MaxPullPoints);
                                        parameters.Add("MaximumNumberOfKeys", MaximumNumberOfKeys);
                                        parameters.Add("MaximumNumberOfCertificates", MaximumNumberOfCertificates);

                                        pst.CheckProfiles(_parameters.Profiles, _features, _scopes, parameters);

                                        //
                                        // if we run only one/several defined test (not Feature definition process, not 0 tests to run),
                                        // we'll have to display profiles support
                                        // And if profiles support have been displayed already (features defined), there is no need
                                        // to notify TestController at all
                                        //

                                        bool defineTests = (processes.Count == 1 &&
                                                            processes.Contains(FeaturesDefinitionProcess.This)) &&
                                                           _parameters.FeatureDefinition != FeatureDefinitionMode.Define;
                                        if (!_featuresDefined || defineTests)
                                        {
                                            InitConformanceTesting(param);

                                            _featuresDefined = true;

                                            List <TestInfo> tests =
                                                ConformanceLogicHandler.GetTestsByFeatures(_parameters.AllTestCases,
                                                                                           param.Features,
                                                                                           _parameters.Conformance);
                                            if (defineTests)
                                            {
                                                // define test cases via features detected
                                                processes.AddRange(tests);
                                            }
                                            ReportInitializationCompleted(tests, defineTests);
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                // pause between tests. If "Halt" is clicked during the pause - exit tests execution.
                                //if (current != processes.Count)
                                if (processNextFlag = curr.MoveNext())
                                {
                                    _currentTest = null;

                                    int hndl = WaitHandle.WaitAny(new WaitHandle[] { _haltEvent },
                                                                  _parameters.TimeBetweenTests);

                                    _haltEvent.Reset();
                                    lock (_pauseSync)
                                    {
                                        halt = _delayedHalt || _stop;
                                    }
                                    if (hndl == 0 || halt)
                                    {
                                        System.Diagnostics.Debug.WriteLine("TEST SEQUENCE HALTED2");
                                        bCompletedNormally = false;
                                        processNextFlag    = false;
                                    }
                                }
                                else
                                {
                                    if (_parameters.RepeatTests)
                                    {
                                        breakFlag = false;
                                    }
                                    bCompletedNormally = true;
                                }
                            }
                        }
                        catch (System.Reflection.TargetException exc)
                        {
                            System.Diagnostics.Debug.WriteLine("TEST SEQUENCE TargetException1");
                            _currentTest.ExitTest(exc);
                            ReportException(exc);
                            if (testInfo.ProcessType == ProcessType.FeatureDefinition)
                            {
                                System.Diagnostics.Debug.WriteLine("TEST SEQUENCE TargetException2");
                                break;
                            }
                        }
                        catch (System.ArgumentException exc)
                        {
                            System.Diagnostics.Debug.WriteLine("TEST SEQUENCE ArgumentException");
                            _currentTest.ExitTest(exc);
                            ReportException(exc);
                        }
                        catch (System.Reflection.TargetParameterCountException exc)
                        {
                            System.Diagnostics.Debug.WriteLine("TEST SEQUENCE TargetParameterCountException");
                            _currentTest.ExitTest(exc);
                            ReportException(exc);
                        }
                        catch (System.MethodAccessException exc)
                        {
                            System.Diagnostics.Debug.WriteLine("TEST SEQUENCE MethodAccessException");
                            _currentTest.ExitTest(exc);
                            ReportException(exc);
                        }
                        catch (System.InvalidOperationException exc)
                        {
                            System.Diagnostics.Debug.WriteLine("TEST SEQUENCE InvalidOperationException");
                            _currentTest.ExitTest(exc);
                            ReportException(exc);
                        }
                        catch (Exception exc)
                        {
                            System.Diagnostics.Debug.WriteLine("TEST SEQUENCE Exception");
                            ReportException(exc);
                        }
                    }
                    processes.EndExecution();
                } while (_parameters.RepeatTests && !breakFlag);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine("TEST SEQUENCE wrap Exception");
            }
            finally
            {
                //If halt command was received and handled before start of waiting on _haltEvent.
                _haltEvent.Reset();
            }

            return(bCompletedNormally);
        }
Пример #12
0
 public static void right()
 {
     Console.Write("Aantal graden: ");
     double graden = double.Parse(Console.ReadLine());
     Console.Write ("Hoe snel: ");
     SByte speed = (SByte)int.Parse(Console.ReadLine());
     Console.WriteLine ("Turning " + graden + " degrees right");
     //Convert degrees to cm. Bereken eerst de graad/Cm en vul deze in bij de constanten
     uint gradencorrect = (uint)(graden * graadCmTurn); //Want graden * graadCm geeft de precieze draai.
     //Hier begint de magie
     waitHandle = vehicle.SpinRight(speed,gradencorrect,true);
     //Geef die motor even rust
     waitHandle.WaitOne();
     string output = graden + " naar rechts gedraaid met een snelheid van " + speed + "%";
     Console.WriteLine (output);
     using (System.IO.StreamWriter file =
         new System.IO.StreamWriter (@"/home/root/apps/NoWait/output.txt", true)) {
         file.WriteLine ("right");
         file.WriteLine (graden);
         file.WriteLine (speed);
         file.WriteLine ("");
     }
     Thread.Sleep (100);
 }
 public static int WaitAny(WaitHandle[] waitHandles, System.TimeSpan timeout, bool exitContext)
 {
 }
Пример #14
0
        public static Task <bool> ToTask(this WaitHandle handle, int timeout = Timeout.Infinite, CancellationToken cancellationToken = default(CancellationToken))
        {
            Requires.NotNull(handle, nameof(handle));

            // Check whether the handle is already signaled as an optimization.
            // But even for WaitOne(0) the CLR can pump messages if called on the UI thread, which the caller may not
            // be expecting at this time, so be sure there is no message pump active by controlling the SynchronizationContext.
            using (NoMessagePumpSyncContext.Default.Apply())
            {
                if (handle.WaitOne(0))
                {
                    return(TrueTask);
                }
                else if (timeout == 0)
                {
                    return(FalseTask);
                }
            }

            cancellationToken.ThrowIfCancellationRequested();
            var tcs = new TaskCompletionSource <bool>();

            // Arrange that if the caller signals their cancellation token that we complete the task
            // we return immediately. Because of the continuation we've scheduled on that task, this
            // will automatically release the wait handle notification as well.
            CancellationTokenRegistration cancellationRegistration =
                cancellationToken.Register(
                    state =>
            {
                var tuple = (Tuple <TaskCompletionSource <bool>, CancellationToken>)state;
                tuple.Item1.TrySetCanceled(tuple.Item2);
            },
                    Tuple.Create(tcs, cancellationToken));

            RegisteredWaitHandle callbackHandle = ThreadPool.RegisterWaitForSingleObject(
                handle,
                (state, timedOut) => ((TaskCompletionSource <bool>)state).TrySetResult(!timedOut),
                state: tcs,
                millisecondsTimeOutInterval: timeout,
                executeOnlyOnce: true);

            // It's important that we guarantee that when the returned task completes (whether cancelled, timed out, or signaled)
            // that we release all resources.
            if (cancellationToken.CanBeCanceled)
            {
                // We have a cancellation token registration and a wait handle registration to release.
                // Use a tuple as a state object to avoid allocating delegates and closures each time this method is called.
                tcs.Task.ContinueWith(
                    (_, state) =>
                {
                    var tuple = (Tuple <RegisteredWaitHandle, CancellationTokenRegistration>)state;
                    tuple.Item1.Unregister(null); // release resources for the async callback
                    tuple.Item2.Dispose();        // release memory for cancellation token registration
                },
                    Tuple.Create <RegisteredWaitHandle, CancellationTokenRegistration>(callbackHandle, cancellationRegistration),
                    CancellationToken.None,
                    TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default);
            }
            else
            {
                // Since the cancellation token was the default one, the only thing we need to track is clearing the RegisteredWaitHandle,
                // so do this such that we allocate as few objects as possible.
                tcs.Task.ContinueWith(
                    (_, state) => ((RegisteredWaitHandle)state).Unregister(null),
                    callbackHandle,
                    CancellationToken.None,
                    TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default);
            }

            return(tcs.Task);
        }
 /// <summary>
 /// See interface docs.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="windowHandle"></param>
 /// <param name="userEventWin32"></param>
 /// <param name="eventHandle"></param>
 /// <param name="configurationIndex"></param>
 public void CreateSimConnect(string name, IntPtr windowHandle, uint userEventWin32, WaitHandle eventHandle, uint configurationIndex)
 {
     _SimConnect                            = new SimConnect("Virtual Radar Server", windowHandle, userEventWin32, eventHandle, configurationIndex);
     _SimConnect.OnRecvEvent               += SimConnect_RecvEvent;
     _SimConnect.OnRecvException           += SimConnect_RecvException;
     _SimConnect.OnRecvQuit                += SimConnect_RecvQuit;
     _SimConnect.OnRecvSimobjectDataBytype += SimConnect_RecvSimobjectDataBytype;
 }
Пример #16
0
 public static async Task WaitAsync(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken = default)
 {
     await WaitAsync(handle, TimeSpan.FromMilliseconds(millisecondsTimeout), cancellationToken);
 }
Пример #17
0
 // http://www.thomaslevesque.com/2015/06/04/async-and-cancellation-support-for-wait-handles/
 public static bool WaitOne(this WaitHandle handle, CancellationToken cancellationToken = default)
 {
     return(WaitOne(handle, Timeout.InfiniteTimeSpan, cancellationToken));
 }
Пример #18
0
 // https://stackoverflow.com/questions/18756354/wrapping-manualresetevent-as-awaitable-task
 public static async Task WaitAsync(this WaitHandle handle, CancellationToken cancellationToken = default)
 {
     await WaitAsync(handle, Timeout.InfiniteTimeSpan, cancellationToken);
 }
Пример #19
0
 public static bool WaitOne(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken = default)
 {
     return(WaitOne(handle, TimeSpan.FromMilliseconds(millisecondsTimeout), cancellationToken));
 }
        /// <summary>
        /// Asserts that the given handle will be signaled within the default timeout.
        /// </summary>
        public static void ExpectEvent(WaitHandle eventOccurred, string eventName_NoRetry)
        {
            string message = string.Format("Didn't observe a {0} event within {1}ms", eventName_NoRetry, WaitForExpectedEventTimeout_NoRetry);

            Assert.True(eventOccurred.WaitOne(WaitForExpectedEventTimeout_NoRetry), message);
        }
Пример #21
0
 internal TimerThread(WaitHandle initEvent)
     : base(initEvent)
 {
 }
Пример #22
0
        async Task <PreprocessingStepParams> ExecuteInternal(IPreprocessingStepCallback callback)
        {
            var trace = callback.Trace;

            using (trace.NewFrame)
            {
                await callback.BecomeLongRunning();

                trace.Info("Downloading '{0}' from '{1}'", sourceFile.FullPath, sourceFile.Location);
                callback.SetStepDescription("Downloading " + sourceFile.FullPath);

                string tmpFileName = callback.TempFilesManager.GenerateNewName();
                trace.Info("Temporary filename to download to: {0}", tmpFileName);

                Action <Stream, long, string> writeToTempFile = (fromStream, contentLength, description) =>
                {
                    using (FileStream fs = new FileStream(tmpFileName, FileMode.Create))
                        using (var progress = contentLength != 0 ? progressAggregator.CreateProgressSink() : (Progress.IProgressEventsSink)null)
                        {
                            IOUtils.CopyStreamWithProgress(fromStream, fs, downloadedBytes =>
                            {
                                callback.SetStepDescription(string.Format("{2} {0}: {1}",
                                                                          IOUtils.FileSizeToString(downloadedBytes), sourceFile.FullPath, description));
                                if (progress != null)
                                {
                                    progress.SetValue((double)downloadedBytes / (double)contentLength);
                                }
                            });
                        }
                };

                var uri = new Uri(sourceFile.Location);
                LogDownloaderRule logDownloaderRule;
                using (var cachedValue = cache.GetValue(uri))
                {
                    if (cachedValue != null)
                    {
                        writeToTempFile(cachedValue, cachedValue.Length, "Loading from cache");
                    }
                    else if ((logDownloaderRule = config.GetLogDownloaderConfig(uri)) != null && logDownloaderRule.UseWebBrowserDownloader)
                    {
                        using (var stream = await webBrowserDownloader.Download(new WebViewTools.DownloadParams()
                        {
                            Location = uri,
                            ExpectedMimeType = logDownloaderRule.ExpectedMimeType,
                            Cancellation = callback.Cancellation,
                            Progress = progressAggregator,
                            IsLoginUrl = testUri => logDownloaderRule.LoginUrls.Any(loginUrl => testUri.GetLeftPart(UriPartial.Path).Contains(loginUrl))
                        }))
                        {
                            writeToTempFile(stream, 0, "Downloading");
                        }
                    }
                    else
                    {
                        using (WebClient client = new WebClient())
                            using (ManualResetEvent completed = new ManualResetEvent(false))
                            {
                                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

                                var credentials = new CredentialsImpl()
                                {
                                    Callback = callback, CredCache = credCache
                                };
                                client.Credentials = credentials;

                                Exception failure = null;
                                client.OpenReadCompleted += (s, evt) =>
                                {
                                    failure = evt.Error;
                                    if (failure != null)
                                    {
                                        trace.Error(failure, "Downloading {0} completed with error", sourceFile.Location);
                                    }
                                    if (failure == null && (evt.Cancelled || callback.Cancellation.IsCancellationRequested))
                                    {
                                        trace.Warning("Downloading {0} cancelled", sourceFile.Location);
                                        failure = new Exception("Aborted");
                                    }
                                    if (failure == null)
                                    {
                                        try
                                        {
                                            long contentLength;
                                            long.TryParse(client.ResponseHeaders["Content-Length"] ?? "", out contentLength);
                                            writeToTempFile(evt.Result, contentLength, "Downloading");
                                        }
                                        catch (Exception e)
                                        {
                                            trace.Error(e, "Failed saving to file");
                                            failure = e;
                                        }
                                    }
                                    completed.Set();
                                };

                                trace.Info("Start downloading {0}", sourceFile.Location);
                                client.OpenReadAsync(uri);

                                if (WaitHandle.WaitAny(new WaitHandle[] { completed, callback.Cancellation.WaitHandle }) == 1)
                                {
                                    trace.Info("Cancellation event was triggered. Cancelling download.");
                                    client.CancelAsync();
                                    completed.WaitOne();
                                }

                                HandleFailure(callback, credentials, failure);

                                using (FileStream fs = new FileStream(tmpFileName, FileMode.Open))
                                {
                                    cache.SetValue(new Uri(sourceFile.Location), fs).Wait();
                                }
                            }
                    }
                }

                string preprocessingStep = name;

                return(new PreprocessingStepParams(
                           tmpFileName, sourceFile.FullPath,
                           sourceFile.PreprocessingHistory.Add(new PreprocessingHistoryItem(preprocessingStep))
                           ));
            }
        }
Пример #23
0
    // ThreadPool::read_uci_options() updates internal threads parameters from the
    // corresponding UCI options and creates/destroys threads to match the requested
    // number. Thread objects are dynamically allocated to avoid creating all possible
    // threads in advance (which include pawns and material tables), even if only a
    // few are to be used.
    internal static void read_uci_options(WaitHandle[] initEvents)
    {
        minimumSplitDepth = int.Parse(OptionMap.Instance["Min Split Depth"].v)*Depth.ONE_PLY;

        var requested = int.Parse(OptionMap.Instance["Threads"].v);
        var current = 0;

        Debug.Assert(requested > 0);

        while (threads.Count < requested)
        {
            if (initEvents == null)
            {
                threads.Add(new Thread(null));
            }
            else
            {
                threads.Add(new Thread(initEvents[current + 2]));
                current++;
            }
        }

        while (threads.Count > requested)
        {
            delete_thread(threads[threads.Count - 1]);
            threads.RemoveAt(threads.Count - 1);
        }
    }
 public void Flush1(ContextType contextType, WaitHandle waitHandle)
 {
     Flush1(contextType, waitHandle.SafeWaitHandle.DangerousGetHandle());
 }
Пример #25
0
        /// <summary>
        /// Get the result of the work item.
        /// If the work item didn't run yet then the caller waits for the result, timeout, or cancel.
        /// In case of error the e argument is filled with the exception
        /// </summary>
        /// <returns>The result of the work item</returns>
        private object GetResult(
            int millisecondsTimeout,
            bool exitContext,
            WaitHandle cancelWaitHandle,
            out Exception e)
        {
            e = null;

            // Check for cancel
            if (WorkItemState.Canceled == GetWorkItemState())
            {
                throw new WorkItemCancelException("Work item canceled");
            }

            // Check for completion
            if (IsCompleted)
            {
                e = _exception;
                return(_result);
            }

            // If no cancelWaitHandle is provided
            if (null == cancelWaitHandle)
            {
                WaitHandle wh = GetWaitHandle();

                bool timeout = !STPEventWaitHandle.WaitOne(wh, millisecondsTimeout, exitContext);

                ReleaseWaitHandle();

                if (timeout)
                {
                    throw new WorkItemTimeoutException("Work item timeout");
                }
            }
            else
            {
                WaitHandle wh     = GetWaitHandle();
                int        result = STPEventWaitHandle.WaitAny(new WaitHandle[] { wh, cancelWaitHandle });
                ReleaseWaitHandle();

                switch (result)
                {
                case 0:
                    // The work item signaled
                    // Note that the signal could be also as a result of canceling the
                    // work item (not the get result)
                    break;

                case 1:
                case STPEventWaitHandle.WaitTimeout:
                    throw new WorkItemTimeoutException("Work item timeout");

                default:
                    Debug.Assert(false);
                    break;
                }
            }

            // Check for cancel
            if (WorkItemState.Canceled == GetWorkItemState())
            {
                throw new WorkItemCancelException("Work item canceled");
            }

            Debug.Assert(IsCompleted);

            e = _exception;

            // Return the result
            return(_result);
        }
Пример #26
0
        private void PlaybackProc(object playbackStartedEventWaithandle)
        {
            Exception exception  = null;
            IntPtr    avrtHandle = IntPtr.Zero;

            try
            {
                int bufferSize = _audioClient.BufferSize;
                int frameSize  = _outputFormat.Channels * _outputFormat.BytesPerSample;

                var buffer = new byte[bufferSize * frameSize];

                WaitHandle[] eventWaitHandleArray = { _eventWaitHandle };

                //001

                /*if (!FeedBuffer(_renderClient, buffer, bufferSize, frameSize)) //todo: might cause a deadlock: play() is waiting on eventhandle but FeedBuffer got already called
                 * {
                 *      _playbackState = PlaybackState.Stopped;
                 *      if (playbackStartedEventWaithandle is EventWaitHandle)
                 *      {
                 *              ((EventWaitHandle)playbackStartedEventWaithandle).Set();
                 *              playbackStartedEventWaithandle = null;
                 *      }
                 * }
                 * else
                 * {*/
                _audioClient.Start();
                _playbackState = PlaybackState.Playing;

                string mmcssType = Latency > 25 ? "Audio" : "Pro Audio";

                int taskIndex;
                avrtHandle = NativeMethods.AvSetMmThreadCharacteristics(mmcssType, out taskIndex);


                if (playbackStartedEventWaithandle is EventWaitHandle)
                {
                    ((EventWaitHandle)playbackStartedEventWaithandle).Set();
                    playbackStartedEventWaithandle = null;
                }

                bool isAudioClientStopped = false;

                while (PlaybackState != PlaybackState.Stopped)
                {
                    //based on the "RenderSharedEventDriven"-Sample: http://msdn.microsoft.com/en-us/library/dd940520(v=vs.85).aspx
                    if (_eventSync)
                    {
                        //3 * latency = see msdn: recommended timeout
                        int eventWaitHandleIndex = WaitHandle.WaitAny(eventWaitHandleArray, 3 * _latency, false);
                        if (eventWaitHandleIndex == WaitHandle.WaitTimeout)
                        {
                            //guarantee that the stopped audio client (in exclusive and eventsync mode) can be
                            //restarted below
                            if (PlaybackState != PlaybackState.Playing && !isAudioClientStopped)
                            {
                                continue;
                            }
                        }
                    }
                    else
                    {
                        //based on the "RenderSharedTimerDriven"-Sample: http://msdn.microsoft.com/en-us/library/dd940521(v=vs.85).aspx
                        Thread.Sleep(_latency / 8);
                    }

                    if (PlaybackState == PlaybackState.Playing)
                    {
                        if (isAudioClientStopped)
                        {
                            //restart the audioclient if it is still paused in exclusive mode
                            //belongs to the bugfix described below. http://cscore.codeplex.com/workitem/23
                            _audioClient.Start();
                            isAudioClientStopped = false;
                        }

                        int padding;
                        if (_eventSync && _shareMode == AudioClientShareMode.Exclusive)
                        {
                            padding = 0;
                        }
                        else
                        {
                            padding = _audioClient.GetCurrentPadding();
                        }

                        int framesReadyToFill = bufferSize - padding;
                        //avoid conversion errors

                        /*if (framesReadyToFill > 5 &&
                         *      !(_source is DmoResampler &&
                         *        ((DmoResampler) _source).OutputToInput(framesReadyToFill * frameSize) <= 0))
                         * {
                         *      if (!FeedBuffer(_renderClient, buffer, framesReadyToFill, frameSize))
                         *              _playbackState = PlaybackState.Stopped; //TODO: Fire Stopped-event here?
                         * }*/

                        if (framesReadyToFill <= 5 ||
                            ((_source is DmoResampler) && ((DmoResampler)_source).OutputToInput(framesReadyToFill * frameSize) <= 0))
                        {
                            continue;
                        }

                        if (!FeedBuffer(_renderClient, buffer, framesReadyToFill, frameSize))
                        {
                            _playbackState = PlaybackState.Stopped;                             //source is eof
                        }
                    }
                    else if (PlaybackState == PlaybackState.Paused &&
                             _shareMode == AudioClientShareMode.Exclusive &&
                             !isAudioClientStopped)
                    {
                        //stop the audioclient on paused if the sharemode is set to exclusive
                        //otherwise there would be a "repetitive" sound. see http://cscore.codeplex.com/workitem/23
                        _audioClient.Stop();
                        isAudioClientStopped = true;
                    }
                }

                if (avrtHandle != IntPtr.Zero)
                {
                    NativeMethods.AvRevertMmThreadCharacteristics(avrtHandle);
                    avrtHandle = IntPtr.Zero;
                }


                Thread.Sleep(_latency / 2);

                _audioClient.Stop();
                _audioClient.Reset();
                //}
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                //set the playbackstate to stopped
                _playbackState = PlaybackState.Stopped;
                if (avrtHandle != IntPtr.Zero)
                {
                    NativeMethods.AvRevertMmThreadCharacteristics(avrtHandle);
                }

                //set the eventWaitHandle since the Play() method maybe still waits on it (only possible if there were any errors during the initialization)
                var eventWaitHandle = playbackStartedEventWaithandle as EventWaitHandle;
                if (eventWaitHandle != null)
                {
                    eventWaitHandle.Set();
                }

                RaiseStopped(exception);
            }
        }
Пример #27
0
 public bool Unregister(WaitHandle waitObject) { throw new NotSupportedException(); }
Пример #28
0
        private unsafe void ReadWriteThread()
        {
            WaitHandle[] handles = new WaitHandle[] {
                m_StopRunning,
                m_Buffer.Serial.ReadBufferNotFull,
                m_Buffer.Serial.WriteBufferNotEmpty
            };
            m_Buffer.WriteEvent += SerialBufferWriteEvent;

            while (m_IsRunning)
            {
                SerialReadWriteEvent rwevent = SerialReadWriteEvent.NoEvent;

                int handle = WaitHandle.WaitAny(handles, -1);
                switch (handle)
                {
                case 0: // StopRunning - Should abort
                    m_IsRunning = false;
                    continue;
                }

                // These are not in the switch statement to ensure that we can actually
                // read/write simultaneously.
                if (m_Buffer.Serial.ReadBufferNotFull.WaitOne(0))
                {
                    rwevent |= SerialReadWriteEvent.ReadEvent;
                }
                if (m_Buffer.Serial.WriteBufferNotEmpty.WaitOne(0))
                {
                    rwevent |= SerialReadWriteEvent.WriteEvent;
                }

                SerialReadWriteEvent result = m_Dll.serial_waitforevent(m_Handle, rwevent, 500);
                if (result == SerialReadWriteEvent.Error)
                {
                    if (Log.SerialTrace(System.Diagnostics.TraceEventType.Error))
                    {
                        Log.Serial.TraceEvent(System.Diagnostics.TraceEventType.Error, 0,
                                              "{0}: ReadWriteThread: Error waiting for event; errno={1}; description={2}",
                                              m_Name, m_Dll.errno, m_Dll.serial_error(m_Handle));
                    }
                    m_IsRunning = false;
                    continue;
                }
                else if (Log.SerialTrace(System.Diagnostics.TraceEventType.Verbose))
                {
                    Log.Serial.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0,
                                          "{0}: ReadWriteThread: serial_waitforevent({1}, {2}) == {3}",
                                          m_Name, m_HandlePtr, rwevent, result);
                }

                if ((result & SerialReadWriteEvent.ReadEvent) != 0)
                {
                    int rresult;
                    fixed(byte *b = m_Buffer.Serial.ReadBuffer.Array)
                    {
                        byte *bo     = b + m_Buffer.Serial.ReadBuffer.End;
                        int   length = m_Buffer.Serial.ReadBuffer.WriteLength;

                        rresult = m_Dll.serial_read(m_Handle, (IntPtr)bo, length);
                        if (rresult < 0)
                        {
                            if (Log.SerialTrace(System.Diagnostics.TraceEventType.Error))
                            {
                                Log.Serial.TraceEvent(System.Diagnostics.TraceEventType.Error, 0,
                                                      "{0}: ReadWriteThread: Error reading data; errno={1}; description={2}",
                                                      m_Name, m_Dll.errno, m_Dll.serial_error(m_Handle));
                            }
                            m_IsRunning = false;
                            continue;
                        }
                        else
                        {
                            if (Log.SerialTrace(System.Diagnostics.TraceEventType.Verbose))
                            {
                                Log.Serial.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0,
                                                      "{0}: ReadWriteThread: serial_read({1}, {2}, {3}) == {4}",
                                                      m_Name, m_HandlePtr, (IntPtr)bo, length, rresult);
                            }
                            if (rresult > 0)
                            {
                                m_Buffer.Serial.ReadBufferProduce(rresult);
                            }
                        }
                    }

                    if (rresult > 0)
                    {
                        OnDataReceived(this, new SerialDataReceivedEventArgs(SerialData.Chars));
                    }
                }

                if ((result & SerialReadWriteEvent.WriteEvent) != 0)
                {
                    int wresult;
                    fixed(byte *b = m_Buffer.Serial.WriteBuffer.Array)
                    {
                        byte *bo     = b + m_Buffer.Serial.WriteBuffer.Start;
                        int   length = m_Buffer.Serial.WriteBuffer.ReadLength;

                        wresult = m_Dll.serial_write(m_Handle, (IntPtr)bo, length);
                        if (wresult < 0)
                        {
                            if (Log.SerialTrace(System.Diagnostics.TraceEventType.Error))
                            {
                                Log.Serial.TraceEvent(System.Diagnostics.TraceEventType.Error, 0,
                                                      "{0}: ReadWriteThread: Error writing data; errno={1}; description={2}",
                                                      m_Name, m_Dll.errno, m_Dll.serial_error(m_Handle));
                            }
                            m_IsRunning = false;
                        }
                        else
                        {
                            if (Log.SerialTrace(System.Diagnostics.TraceEventType.Verbose))
                            {
                                Log.Serial.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0,
                                                      "{0}: ReadWriteThread: serial_write({1}, {2}, {3}) == {4}",
                                                      m_Name, m_HandlePtr, (IntPtr)bo, length, wresult);
                            }
                            if (wresult > 0)
                            {
                                m_Buffer.Serial.WriteBufferConsume(wresult);
                                m_Buffer.Serial.TxEmptyEvent();
                            }
                        }
                    }
                }
            }
            m_Buffer.WriteEvent -= SerialBufferWriteEvent;

            // Clear the write buffer. Anything that's still in the driver serial buffer will continue to write. The I/O was cancelled
            // so no need to purge the actual driver itself.
            m_Buffer.Serial.Purge();

            // We must notify the stream that any blocking waits should abort.
            m_Buffer.Serial.DeviceDead();
        }
	public AbandonedMutexException(string message, int location, WaitHandle handle) {}
Пример #30
0
    // Clears an existing subscription
    private void ClearSubscription()
    {
        // Reset subscription state
        m_subscribed = false;
        m_linesInitializedWaitHandle = null;

        // Clear out existing scales
        if ((object)m_scales != null)
            m_scales.Clear();

        // Erase data lines
        if ((object)m_dataLines != null)
        {
            foreach (DataLine dataLine in m_dataLines.Values)
                UIThread.Invoke(EraseLine, dataLine);

            m_dataLines.Clear();
        }

        // Erase legend lines
        if ((object)m_legendLines != null)
        {
            foreach (LegendLine legendLine in m_legendLines)
                UIThread.Invoke(EraseLine, legendLine);

            m_legendLines.Clear();
        }

        // Clear legend text
        m_legendMesh.UpdateText("");
    }
Пример #31
0
 public NotAsyncLie(object state)
 {
     AsyncState      = state;
     AsyncWaitHandle = new ManualResetEvent(true);
 }
 public TResult GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e)
 {
     return((TResult)_workItemResult.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e));
 }
Пример #33
0
        /// <summary>
        /// Waits for the operation to complete.
        /// </summary>
        /// <returns>True if operation completed without any errors.</returns>
        public bool WaitForComplete()
        {
            try
            {
                WaitHandle waitHandle = null;

                int timeout = Timeout.Infinite;

                lock (m_lock)
                {
                    if (m_exception != null)
                    {
                        throw new ServiceResultException(m_exception, StatusCodes.BadCommunicationError);
                    }

                    if (m_deadline != DateTime.MinValue)
                    {
                        timeout = (int)(m_deadline - DateTime.UtcNow).TotalMilliseconds;

                        if (timeout <= 0)
                        {
                            return(false);
                        }
                    }

                    if (m_isCompleted)
                    {
                        return(true);
                    }

                    if (m_waitHandle == null)
                    {
                        m_waitHandle = new ManualResetEvent(false);
                    }

                    waitHandle = m_waitHandle;
                }

                if (waitHandle != null)
                {
                    try
                    {
                        #if !SILVERLIGHT
                        if (!m_waitHandle.WaitOne(timeout, false))
                        {
                            return(false);
                        }
                        #else
                        if (!m_waitHandle.WaitOne(timeout))
                        {
                            return(false);
                        }
                        #endif

                        lock (m_lock)
                        {
                            if (m_exception != null)
                            {
                                throw new ServiceResultException(m_exception, StatusCodes.BadCommunicationError);
                            }
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        return(false);
                    }
                }
            }
            finally
            {
                // always stop the timer after operation completes.
                lock (m_lock)
                {
                    if (m_timer != null)
                    {
                        try
                        {
                            m_timer.Dispose();
                            m_timer = null;
                        }
                        catch (Exception)
                        {
                            // ignore
                        }
                    }
                }

                // release the wait event.
                if (m_waitHandle != null)
                {
                    try
                    {
                        m_waitHandle.Close();
                        m_waitHandle = null;
                    }
                    catch (Exception)
                    {
                        // ignore
                    }
                }
            }

            return(true);
        }
Пример #34
0
        public override Errors SaveChanges()
        {
            Errors errRes = Errors.NoError,
                   bErr   = Errors.NoError;
            int indxEv    = -1;

            m_evSaveChangesComplete.Reset();

            lock (m_lockResSaveChanges)
            {
                m_listResSaveChanges.Clear();
            }

            int prevIndxTECComponent = indxTECComponents;

            foreach (RDGStruct [] curRDGValues in m_listCurRDGValues)
            {
                bErr = Errors.NoError;

                for (INDEX_WAITHANDLE_REASON i = INDEX_WAITHANDLE_REASON.ERROR; i < (INDEX_WAITHANDLE_REASON.ERROR + 1); i++)
                {
                    ((ManualResetEvent)m_waitHandleState[(int)i]).Reset();
                }

                if (modeTECComponent(m_listTECComponentIndexDetail[m_listCurRDGValues.IndexOf(curRDGValues)]) == FormChangeMode.MODE_TECCOMPONENT.TG)
                {
                    indxEv = WaitHandle.WaitAny(m_waitHandleState);
                    if (indxEv == 0)
                    {
                        indxTECComponents = m_listTECComponentIndexDetail[m_listCurRDGValues.IndexOf(curRDGValues)];

                        curRDGValues.CopyTo(m_curRDGValues, 0);

                        bErr = base.SaveChanges();
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    ;
                }

                lock (m_lockResSaveChanges)
                {
                    m_listResSaveChanges.Add(bErr);

                    if (!(bErr == Errors.NoError) && (errRes == Errors.NoError))
                    {
                        errRes = bErr;
                    }
                    else
                    {
                        ;
                    }
                }
            }

            indxTECComponents = prevIndxTECComponent;

            //if (indxEv == 0)
            //if (errRes == Errors.NoError)
            m_evSaveChangesComplete.Set();
            //else ;

            if (!(saveComplete == null))
            {
                saveComplete();
            }
            else
            {
                ;
            }

            return(errRes);
        }
Пример #35
0
    public static void ExpectEvent(WaitHandle eventOccured, string eventName, int timeout = Utility.Timeout)
    {
        string message = String.Format("Didn't observe a {0} event within {1}ms", eventName, timeout);

        Assert.True(eventOccured.WaitOne(timeout), message);
    }
Пример #36
0
    public static void ExpectNoEvent(WaitHandle eventOccured, string eventName, int timeout = Utility.Timeout)
    {
        string message = String.Format("Should not observe a {0} event", eventName);

        Assert.False(eventOccured.WaitOne(timeout), message);
    }
Пример #37
0
 public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce)
 {
     return RegisterWaitForSingleObject(waitObject, callBack, state, (long)millisecondsTimeOutInterval, executeOnlyOnce);
 }
Пример #38
0
 public static void workThread()
 {
     #region 获取本地可用IP地址
     strLocalHAddr = null;
     IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
     //检测可用网卡网关值,确定是否可用
     NetworkInterface[] NetWorkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
     foreach (NetworkInterface NetworkIntf in NetWorkInterfaces)
     {
         IPInterfaceProperties IpInterPro = NetworkIntf.GetIPProperties();
         UnicastIPAddressInformationCollection uniIPAInfoCol = IpInterPro.UnicastAddresses;
         foreach (UnicastIPAddressInformation UniCIPAInfo in uniIPAInfoCol)
         {
             if ((UniCIPAInfo.Address.AddressFamily == AddressFamily.InterNetwork) && (UniCIPAInfo.IPv4Mask != null))
             {
                 if (IpInterPro.GatewayAddresses.Count != 0)
                 {
                     //IpInterPro.GatewayAddresses的count为0,所以[0]也超出索引范围
                     //所以先将网关地址做长度判断
                     if (IpInterPro.GatewayAddresses[0].Address.ToString().CompareTo("0.0.0.0") != 0)
                     {
                         strLocalHAddr = UniCIPAInfo.Address.ToString();
                         break;
                     }
                 }
             }
         }
     }
     if (strLocalHAddr == null)
     {
         //无可用网络
         MessageBox.Show("无可用网络连接,请检查网络");
     }
     else
     {
         strLocalHAddr = strLocalHAddr.Substring(0, strLocalHAddr.LastIndexOf('.') + 1) + "255";
     }
     #endregion 获取本地可用IP地址
     #region 绑定查找服务的UDP对象
     udpSearchRecvDataBuf = new byte[1024];
     sockUdpSearchRecv    = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     //绑定接收服务器UDP数据的RECV_PORT端口
     IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9096);
     sockUdpSearchRecv.Bind(iep);
     remoteUdpEp = new IPEndPoint(IPAddress.Any, 0);
     sockUdpSearchRecv.BeginReceiveFrom(udpSearchRecvDataBuf, 0, 1024, SocketFlags.None, ref remoteUdpEp, UdpSearchReceiveCallback, new object());
     #endregion
     #region 发送广播包查找服务器
     //创建使用UDP发送数据的Socket对象
     sockUdpSearchSend = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     //设置该socket实例的发送形式
     sockUdpSearchSend.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
     SearchServerIpEP = new IPEndPoint(IPAddress.Parse(strLocalHAddr), SEARCH_SEND_PORT);
     udpDataSendBuf   = Encoding.UTF8.GetBytes("are you online?");
     sendDataLen      = udpDataSendBuf.Length;
     //向服务器发送探测包
     sockUdpSearchSend.SendTo(udpDataSendBuf, sendDataLen, SocketFlags.None, SearchServerIpEP);
     //等待服务器响应
     ManualResetEvent[] mrEventAl = new ManualResetEvent[2];
     mrEventAl[0] = mrEventGotServer;
     mrEventAl[1] = mrEventTermiThread;
     int eventIndex = WaitHandle.WaitAny(mrEventAl, 500);
     while (eventIndex != 1)
     {
         eventIndex = WaitHandle.WaitAny(mrEventAl, 500);
     }
     #endregion
 }
Пример #39
0
 internal Thread(WaitHandle initEvent)
     : base(initEvent)
 {
     searching = false;
     maxPly = 0;
     splitPointsSize = 0;
     activeSplitPoint = null;
     activePosition = null;
     idx = ThreadPool.threads.Count; // Starts from 0
     for (var j = 0; j < _.MAX_SPLITPOINTS_PER_THREAD; j++)
     {
         splitPoints[j] = new SplitPoint();
     }
 }
 public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn)
 {
 }
Пример #41
0
    internal volatile bool thinking = true; // Avoid a race with start_thinking()

    internal MainThread(WaitHandle initEvent)
        : base(initEvent)
    {
    }
 public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext)
 {
 }
Пример #43
0
    // ThreadPool::init() is called at startup to create and launch requested threads,
    // that will go immediately to sleep. We cannot use a c'tor because Threads is a
    // static object and we need a fully initialized engine at this point due to
    // allocation of Endgames in Thread c'tor.
    internal static void init()
    {
        var requested = int.Parse(OptionMap.Instance["Threads"].v);
        WaitHandle[] initEvents = new WaitHandle[requested + 1];
        for (var i = 0; i < (requested + 1); i++)
        {
            initEvents[i] = new ManualResetEvent(false);
        }

        System.Threading.ThreadPool.QueueUserWorkItem(launch_threads, initEvents);
        WaitHandle.WaitAll(initEvents);
    }
 public static bool WaitAll(WaitHandle[] waitHandles)
 {
 }
Пример #45
0
 private void WaitWithCancellation(WaitHandle waitHandle, CancellationToken token)
 {
     WaitHandle.WaitAny(new WaitHandle[] { waitHandle, token.WaitHandle });
     token.ThrowIfCancellationRequested();
 }
Пример #46
0
        /// <summary>
        /// Wait for all work items to complete
        /// </summary>
        /// <param name="waitableResults">Array of work item result objects</param>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
        /// <param name="exitContext">
        /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
        /// </param>
        /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
        /// <returns>
        /// true when every work item in waitableResults has completed; otherwise false.
        /// </returns>
        internal static bool WaitAll(
            IWaitableResult[] waitableResults,
            int millisecondsTimeout,
            bool exitContext,
            WaitHandle cancelWaitHandle)
        {
            if (0 == waitableResults.Length)
            {
                return(true);
            }

            bool success;

            WaitHandle[] waitHandles = new WaitHandle[waitableResults.Length];
            GetWaitHandles(waitableResults, waitHandles);

            if ((null == cancelWaitHandle) && (waitHandles.Length <= 64))
            {
                success = STPEventWaitHandle.WaitAll(waitHandles, millisecondsTimeout, exitContext);
            }
            else
            {
                success = true;
                int       millisecondsLeft = millisecondsTimeout;
                Stopwatch stopwatch        = Stopwatch.StartNew();

                WaitHandle[] whs;
                if (null != cancelWaitHandle)
                {
                    whs = new WaitHandle[] { null, cancelWaitHandle };
                }
                else
                {
                    whs = new WaitHandle[] { null };
                }

                bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout);
                // Iterate over the wait handles and wait for each one to complete.
                // We cannot use WaitHandle.WaitAll directly, because the cancelWaitHandle
                // won't affect it.
                // Each iteration we update the time left for the timeout.
                for (int i = 0; i < waitableResults.Length; ++i)
                {
                    // WaitAny don't work with negative numbers
                    if (!waitInfinitely && (millisecondsLeft < 0))
                    {
                        success = false;
                        break;
                    }

                    whs[0] = waitHandles[i];
                    int result = STPEventWaitHandle.WaitAny(whs, millisecondsLeft, exitContext);
                    if ((result > 0) || (STPEventWaitHandle.WaitTimeout == result))
                    {
                        success = false;
                        break;
                    }

                    if (!waitInfinitely)
                    {
                        // Update the time left to wait
                        millisecondsLeft = millisecondsTimeout - (int)stopwatch.ElapsedMilliseconds;
                    }
                }
            }
            // Release the wait handles
            ReleaseWaitHandles(waitableResults);

            return(success);
        }
 public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, System.TimeSpan timeout, bool exitContext)
 {
 }
Пример #48
0
		/// <summary>
		/// Worker function for line counting threads.
		/// </summary>
		private void CountLines()
		{
			// Loop through file names.  When all of the file names have been processed
			// a break is called to exit the loop.
			while (true)
			{
				string filename;

				// Acquire the next file name, insuring we don't miss a name by using a
				// lock to limit access to one thread at a time.
				_fileNameLock.AcquireWriterLock(-1);
				if (_currentFile >= _files.Count)
				{
					// No more files, release the lock and break out of while loop.
					_fileNameLock.ReleaseWriterLock();

					// Figure out which thread we are and signal the event that says we are done with
					// our work.  We have to wait here until all threads are done because each thread
					// updates the GUI with it's results after a file has been processed and the next
					// step is to 
					int name = System.Convert.ToInt32(Thread.CurrentThread.Name);
					_threadDoneEvents[name].Set();
					WaitHandle.WaitAll(_threadDoneEvents);

					// We are locking this part with a semaphore to make sure only one gets access at a
					// time.  That way we don't have a race condition to calling the thread joining and
					// final GUI update.  Note, because of this semaphore it might not be strickly necessary
					// to join the threads (they are done with their work by that time), but it doesn't matter
					// anyway.
					_jointhreadsemaphore.WaitOne();

					// Make sure we don't try to rejoin threads and reactive the controls once they 
					// have already been joined.
					if (!_startedThreadJoin)
					{
						_startedThreadJoin = true;
						this.BeginInvoke(new UICallBack(JoinThreads));
					}
					_jointhreadsemaphore.Release();
					break;
				}

				filename = _files[_currentFile++].ToString();
				_fileNameLock.ReleaseWriterLock();

				// Use local counters so that we can process an entire file and then update the
				// master counters and gui.  This limits the number of read/write locks required
				// and the number of gui updates to a reasonable amount so that the counting isn't
				// done too slowly.
				LineCounts linecounts = _fileTypes.Count(filename);

				// Update the line counters and display.
				_lineCountLock.AcquireWriterLock(-1);
				_lineCounts += linecounts;

				// Update the file counter and display.
				_fileCount++;
				_lineCountLock.ReleaseWriterLock();

				// Do callback to update the user interface.
				this.Invoke(new UICallBack(UpdateUICounts));
			}
		}
 public static bool WaitAll(WaitHandle[] waitHandles, System.TimeSpan timeout, bool exitContext)
 {
 }
Пример #50
0
 public LoginFailInfo(DateTime lastAttempt)
 {
     Count       = 1;
     LastAttempt = lastAttempt;
     Handle      = new EventWaitHandle(false, EventResetMode.ManualReset);
 }
 public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
 {
 }
        internal byte[] Receive(TimeSpan timeout, BufferManager  bm, out int messageLength, out SsbConversationContext conversation,WaitHandle cancelEvent)
        {
            ThrowIfDisposedOrNotOpen();

            byte[] message = null;
            conversation = null;
            messageLength = 0;

            if (queuedResult != null)
            {
                ReceivedMessage r = queuedResult;
                queuedResult = null;
                conversation = r.Conversation;
                messageLength = r.MessageLength;
                byte[] buf = bm.TakeBuffer(messageLength);
                Buffer.BlockCopy(r.MessageBody, 0, buf, 0, messageLength);
                return buf;
            }
            try
            {
                lock (rdrlock)
                {
                    

                    //If this is the first time, open the reader, otherwise read the next row
                    if ( rdr == null || !rdr.Read() )
                    {
                        //the last bactch has been processed.  Close the reader.
                        if (rdr != null)
                        {
                            rdr.Close();
                        }

                        rdr = GetMessageBatch(timeout,cancelEvent);

                        //this is a timeout condition
                        //caused by aborting or closing the reciever
                        if ( rdr == null )
                        {
                            return null;
                        }

                        //this is a timeout condition caused by the WAITFOR expiring
                        if( !rdr.Read() )
                        {
                            rdr.Close();

                            //return the Receiver to it's initial state.
                            rdr = null;
                            return null;
                        }
                    }


                    int i = 0;
                    int conversation_handle = i++;
                    int service_name = i++;
                    int message_type_name = i++;
                    int message_body = i++;
                    int message_sequence_number = i++;
                    Guid conversationHandle = rdr.GetGuid(conversation_handle);
                    string ServiceName = rdr.GetString(service_name);
                    string messageTypeName = rdr.GetString(message_type_name);
                    if (messageTypeName != SsbConstants.SsbEndDialogMessage  && messageTypeName != SsbConstants.SsbDialogTimerMessage)
                    {
                                             

                        //this eliminates a one copy because the message_body 
                        //isn't copied into the row buffer.  Instead it's chunked directly
                        //into the message byte[].
                        // CONSIDER (dbrowne) wraping the reader in a custom stream implementation
                        //and pass that back instead to eliminate another copy.
                        messageLength = (int)rdr.GetBytes(message_body, 0, null, 0, 0);
                        if (bm == null)
                        {
                            message = new byte[messageLength];
                        }
                        else
                        {
                            message = bm.TakeBuffer(messageLength);
                        }
                        int br = (int)rdr.GetBytes(message_body, 0, message, 0, messageLength);
                        if (br != messageLength) //should never happen
                        {
                            throw new Exception("Failed to read all the message bytes");
                        }
                    }

                    long sequence = rdr.GetInt64(message_sequence_number);
                    conversation = new SsbConversationContext(conversationHandle, this.cgId, sequence, messageTypeName);

                    if (messageTypeName == SsbConstants.SsbErrorMessage)
                    {
                        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                        doc.Load(new System.IO.MemoryStream(message, 0, messageLength));

                        System.Xml.XmlNamespaceManager mgr = new System.Xml.XmlNamespaceManager(doc.NameTable);
                        mgr.AddNamespace("er", SsbConstants.SsbErrorMessage);
                        int code = int.Parse(doc.SelectSingleNode("/er:Error/er:Code", mgr).InnerText);
                        string ermsg = doc.SelectSingleNode("/er:Error/er:Description", mgr).InnerText;

                        throw new ProtocolException(string.Format("Service Broker Error Message {0}: {1}", code, ermsg));
                    }

                    SsbInstrumentation.MessageRecieved(messageLength);
                    return message;

                    //if (messageTypeName == SsbConstants.SsbDialogTimerMessage)
                    //{
                    //    //well now we're running again after a lag, now what?
                        
                    //}
                    
                }
                
            }
            catch (SqlException ex)
            {
                //the timeout will not result in a SqlExecption since the timeout value is passed to WAITFOR RECIEVE
                //if (!helper.IsTimeRemaining)
                //{
                //    throw new TimeoutException(String.Format("Timed out while receiving. Timeout value was {0} seconds", timeout.TotalSeconds), ex);
                //}
                
              throw new CommunicationException(String.Format("An exception occurred while receiving from conversation group {0}.", this.cgId), ex);
            }
        }
 public static int WaitAny(WaitHandle[] waitHandles)
 {
 }
Пример #54
0
 /// <summary>
 /// Wait for the specified handle to be signaled.
 /// </summary>
 /// <param name="handle">Handle to wait on.</param>
 /// <param name="cancellationSource">Cancellation token source to cancel if the user hits the cancel button.</param>
 public void Wait(WaitHandle handle, CancellationTokenSource cancellationSource)
 {
     throw new NotImplementedException();
 }
Пример #55
0
 public static void ExpectEvent(WaitHandle eventOccurred, string eventName, int timeout = WaitForExpectedEventTimeout)
 {
     string message = String.Format("Didn't observe a {0} event within {1}ms", eventName, timeout);
     Assert.True(eventOccurred.WaitOne(timeout), message);
 }
Пример #56
0
        /// <summary>
        /// Capture thread - captures audio from WASAPI, resampling it if necessary.
        /// </summary>
        private void DoCaptureThread()
        {
            bool stillPlaying   = true;
            int  mmcssHandle    = 0;
            int  mmcssTaskIndex = 0;

            mmcssHandle = NativeMethods.AvSetMmThreadCharacteristics("Audio", ref mmcssTaskIndex);

            WaitHandle[] waitArray = this.isEventDriven ?
                                     new WaitHandle[] { this.shutdownEvent, this.audioAvailableEvent } :
            new WaitHandle[] { this.shutdownEvent };

            int waitTimeout = this.isEventDriven ? Timeout.Infinite : this.engineLatencyInMs;

            while (stillPlaying)
            {
                // We want to wait for half the desired latency in milliseconds.
                // That way we'll wake up half way through the processing period to pull the
                // next set of samples from the engine.
                int waitResult = WaitHandle.WaitAny(waitArray, waitTimeout);

                switch (waitResult)
                {
                case 0:
                    // If shutdownEvent has been set, we're done and should exit the main capture loop.
                    stillPlaying = false;
                    break;

                default:
                {
                    // We need to retrieve the next buffer of samples from the audio capturer.
                    IntPtr dataPointer;
                    int    framesAvailable;
                    int    flags;
                    long   bufferPosition;
                    long   qpcPosition;
                    bool   isEmpty         = false;
                    long   lastQpcPosition = 0;

                    // Keep fetching audio in a tight loop as long as audio device still has data.
                    while (!isEmpty && !this.shutdownEvent.WaitOne(0))
                    {
                        int hr = this.captureClient.GetBuffer(out dataPointer, out framesAvailable, out flags, out bufferPosition, out qpcPosition);
                        if (hr >= 0)
                        {
                            if ((hr == AudioClientBufferEmpty) || (framesAvailable == 0))
                            {
                                isEmpty = true;
                            }
                            else
                            {
                                int bytesAvailable = framesAvailable * this.mixFrameSize;

                                unsafe
                                {
                                    // The flags on capture tell us information about the data.
                                    // We only really care about the silent flag since we want to put frames of silence into the buffer
                                    // when we receive silence.  We rely on the fact that a logical bit 0 is silence for both float and int formats.
                                    if ((flags & (int)AudioClientBufferFlags.Silent) != 0)
                                    {
                                        // Fill 0s from the capture buffer to the output buffer.
                                        float *ptr = (float *)dataPointer.ToPointer();
                                        for (int i = 0; i < bytesAvailable / sizeof(float); i++)
                                        {
                                            *(ptr + i) = 0f;
                                        }
                                    }
                                    else if (this.gain != 1.0f)
                                    {
                                        // Apply gain on the raw buffer if needed, before the resampler.
                                        // When we capture in shared mode the capture mix format is always 32-bit IEEE
                                        // floating point, so we can safely assume float samples in the buffer.
                                        float *ptr = (float *)dataPointer.ToPointer();
                                        for (int i = 0; i < bytesAvailable / sizeof(float); i++)
                                        {
                                            *(ptr + i) *= this.gain;
                                        }
                                    }
                                }

                                // Check if we need to resample
                                if (this.resampler != null)
                                {
                                    // Process input to resampler
                                    this.ProcessResamplerInput(dataPointer, bytesAvailable, flags, qpcPosition);

                                    // Process output from resampler
                                    int bytesWritten = this.ProcessResamplerOutput();

                                    // Audio capture was successful, so bump the capture buffer pointer.
                                    this.bytesCaptured += bytesWritten;
                                }
                                else
                                {
                                    // Invoke the callback directly to handle the captured samples
                                    if (this.dataAvailableCallback != null)
                                    {
                                        if (qpcPosition > lastQpcPosition)
                                        {
                                            this.dataAvailableCallback(dataPointer, bytesAvailable, qpcPosition);
                                            lastQpcPosition = qpcPosition;

                                            this.bytesCaptured += bytesAvailable;
                                        }
                                        else
                                        {
                                            Console.WriteLine("QPC is less than last {0}", qpcPosition - lastQpcPosition);
                                        }
                                    }
                                }
                            }

                            this.captureClient.ReleaseBuffer(framesAvailable);
                        }
                    }
                }

                break;
                }
            }

            if (mmcssHandle != 0)
            {
                NativeMethods.AvRevertMmThreadCharacteristics(mmcssHandle);
            }
        }
	public AbandonedMutexException(int location, WaitHandle handle) {}
Пример #58
0
 internal ExCommsCallbackServiceChannelFactory(IExecutorService executorService, C callbackInstance,
                                               int timeoutInMilliseconds, WaitHandle canListen)
     : base(executorService, timeoutInMilliseconds, canListen)
 {
     _callbackInstance = callbackInstance;
 }
	public AbandonedMutexException(string message, System.Exception inner, int location, WaitHandle handle) {}
Пример #60
0
        /// <summary>
        ///   Worker thread.
        /// </summary>
        ///
        private void WorkerThread()
        {
            int samples = bufferSize / sizeof(float);

            try
            {
                // The first write should fill the entire buffer.
                var request = new NewFrameRequestedEventArgs(samples);
                NewFrameRequested.Invoke(this, request);

                buffer.Write(request.Buffer, 0, LockFlags.None);

                // The buffer starts playing.
                buffer.Play(0, PlayFlags.Looping);

                int  framesPlayed             = request.FrameIndex;
                int  lastNotificationLocation = 0;
                bool requestedToStop          = false;

                while (!stop)
                {
                    int positionIndex = WaitHandle.WaitAny(waitHandles);

                    if (stop)
                    {
                        break;
                    }


                    if (positionIndex == firstHalfBufferIndex ||
                        positionIndex == secondHalfBufferIndex)
                    {
                        if (requestedToStop)
                        {
                            break;
                        }

                        // When the first half of the buffer has finished
                        //  playing and we have just started playing the
                        //  second half, we will write the next samples in
                        //  the first half of the buffer again.

                        // When the second half of the buffer has finished
                        //  playing, the first half of the buffer will
                        //  start playing again (since this is a circular
                        //  buffer). At this time, we can write the next
                        //  samples in the second half of the buffer.

                        request.Frames = samples / 2;
                        NewFrameRequested(this, request);
                        requestedToStop = request.Stop;

                        int offset = (positionIndex == firstHalfBufferIndex) ? 0 : bufferSize / 2;

                        buffer.Write(request.Buffer, 0, request.Frames, offset, LockFlags.None);
                    }

                    if (positionIndex != secondHalfBufferIndex)
                    {
                        // Notify progress
                        int currentBufferLocation = notifications[positionIndex].Offset;

                        if (lastNotificationLocation >= currentBufferLocation)
                        {
                            lastNotificationLocation = -(bufferSize - lastNotificationLocation);
                        }

                        int delta = (currentBufferLocation - lastNotificationLocation);

                        framesPlayed += delta / sizeof(float);

                        lastNotificationLocation = currentBufferLocation;

                        OnFramePlayingStarted(new PlayFrameEventArgs(framesPlayed, delta));
                    }
                }
            }
            catch (Exception ex)
            {
                if (AudioOutputError != null)
                {
                    AudioOutputError(this, new AudioOutputErrorEventArgs(ex.Message));
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                buffer.Stop();

                OnStopped(EventArgs.Empty);
            }
        }