Example #1
0
        public TItem Dequeue(CancellationToken cancellationToken = default)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                lock (_syncRoot)
                {
                    if (_items.Count > 0)
                    {
                        var item = _items.First.Value;
                        _items.RemoveFirst();

                        return(item);
                    }

                    if (_items.Count == 0)
                    {
                        _gate?.Reset();
                    }
                }

                _gate?.Wait(cancellationToken);
            }

            throw new OperationCanceledException();
        }
Example #2
0
 public void WaitOne()
 {
     if (!_disposing.Value)
     {
         _mreCompleted?.Wait();
     }
 }
Example #3
0
        private static void AttachCtrlcSigtermShutdown(
            CancellationTokenSource cts, ManualResetEventSlim resetEvent, string shutdownMessage)
        {
            void Shutdown()
            {
                if (!cts.IsCancellationRequested)
                {
                    if (!string.IsNullOrEmpty(shutdownMessage))
                    {
                        Console.WriteLine(shutdownMessage);
                    }
                    try
                    {
                        cts.Cancel();
                    }
                    catch (ObjectDisposedException) { }
                }

                // Wait on the given reset event
                resetEvent?.Wait();
            };

            AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => Shutdown();
            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                Shutdown();
                // Don't terminate the process immediately, wait for the Main thread to exit gracefully.
                eventArgs.Cancel = true;
            };
        }
            public WorkParcel GetParcel()
            {
                EnsureNotOnThread(); // Only the background thread can get a parcel

                lock (_disposeLock)
                {
                    if (_disposed)
                    {
                        return(WorkParcel.Empty);
                    }
                }

                _hasParcel?.Wait(_cancelSource.Token);

                lock (_disposeLock)
                {
                    if (_disposed)
                    {
                        return(WorkParcel.Empty);
                    }

                    _hasParcel.Reset();

                    lock (_stateLock)
                    {
                        // Create a cancellation source for this parcel
                        _currentParcelCancelSource = new CancellationTokenSource();

                        var changes = _changes;
                        _changes = new List <ChangeReference>();
                        return(new WorkParcel(changes, _currentParcelCancelSource.Token));
                    }
                }
            }
        // Run in a dedicated thread
        private async void PerformRead()
        {
            var original = _readWriteCancellationTokenSource;

            if (original == null)
            {
                Log.To.Sync.V(Tag, "_readWriteCancellationTokenSource is null, cancelling read...");
                return;
            }

            var zeroByteCount = 0;
            // This will protect us against future nullification of the original source
            var cancelSource = CancellationTokenSource.CreateLinkedTokenSource(original.Token);

            while (!cancelSource.IsCancellationRequested)
            {
                try {
                    _receivePause?.Wait(cancelSource.Token);
                } catch (ObjectDisposedException) {
                    return;
                } catch (OperationCanceledException) {
                    return;
                }

                try {
                    var stream = NetworkStream;
                    if (stream == null)
                    {
                        return;
                    }

                    // Phew, at this point we are clear to actually read from the stream
                    var received = await stream.ReadAsync(_buffer, 0, _buffer.Length, cancelSource.Token).ConfigureAwait(false);

                    if (received == 0)
                    {
                        if (zeroByteCount++ >= 10)
                        {
                            Log.To.Sync.I(Tag, "Failed to read from stream too many times, signaling closed...");
                            DidClose(new CouchbasePosixException(PosixBase.GetCode(nameof(PosixWindows.ECONNRESET))));
                            return;
                        }

                        // Should only happen on a closed stream, but just in case let's continue
                        // after a small delay (wait for cancellation to confirm)
                        Thread.Sleep(200);
                        continue;
                    }

                    zeroByteCount = 0;
                    var data = _buffer.Take(received).ToArray();
                    Receive(data);
                } catch (Exception e) {
                    DidClose(e);
                    return;
                }
            }
        }
        public static void CancelBeforeWait()
        {
            ManualResetEventSlim mres = new ManualResetEventSlim();
            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);

            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(millisec, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(timeSpan, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            mres.Dispose();
        }
Example #7
0
        public void Successful_AppObserver_Run_Cancellation_Via_ObserverManager()
        {
            ObserverManager.FabricServiceContext = this.context;
            ObserverManager.TelemetryEnabled     = false;
            ObserverManager.EtwEnabled           = false;
            ObserverManager.FabricClientInstance = new FabricClient(FabricClientRole.User);

            var stopWatch = new Stopwatch();

            var obs = new AppObserver
            {
                IsEnabled = true,
                NodeName  = "_Test_0",
                IsTestRun = true,
            };

            var obsMgr = new ObserverManager(obs)
            {
                ApplicationName = "fabric:/TestApp0",
            };

            var objReady = new ManualResetEventSlim(false);

            stopWatch.Start();
            var t = Task.Factory.StartNew(() =>
            {
                objReady.Set();
                obsMgr.StartObservers();
            });

            objReady?.Wait();

            while (!obsMgr.IsObserverRunning && stopWatch.Elapsed.TotalSeconds < 10)
            {
                // wait...
            }

            stopWatch.Stop();

            // Observer is running. Stop it...
            obsMgr.StopObservers();
            Thread.Sleep(5);

            Assert.IsFalse(obsMgr.IsObserverRunning);

            obs.Dispose();
            objReady?.Dispose();
        }
Example #8
0
        public static void OnCompleted_CompletesInAnotherSynchronizationContext(bool generic, bool? continueOnCapturedContext)
        {
            SynchronizationContext origCtx = SynchronizationContext.Current;
            try
            {
                // Create a context that tracks operations, and set it as current
                var validateCtx = new ValidateCorrectContextSynchronizationContext();
                Assert.Equal(0, validateCtx.PostCount);
                SynchronizationContext.SetSynchronizationContext(validateCtx);

                // Create a not-completed task and get an awaiter for it
                var mres = new ManualResetEventSlim();
                var tcs = new TaskCompletionSource<object>();

                // Hook up a callback
                bool postedInContext = false;
                Action callback = () =>
                {
                    postedInContext = ValidateCorrectContextSynchronizationContext.IsPostedInContext;
                    mres.Set();
                };
                if (generic)
                {
                    if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                    else tcs.Task.GetAwaiter().OnCompleted(callback);
                }
                else
                {
                    if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                    else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
                }
                Assert.False(mres.IsSet, "Callback should not yet have run.");

                // Complete the task in another context and wait for the callback to run
                Task.Run(() => tcs.SetResult(null));
                mres.Wait();

                // Validate the callback ran and in the correct context
                bool shouldHavePosted = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
                Assert.Equal(shouldHavePosted ? 1 : 0, validateCtx.PostCount);
                Assert.Equal(shouldHavePosted, postedInContext);
            }
            finally
            {
                // Reset back to the original context
                SynchronizationContext.SetSynchronizationContext(origCtx);
            }
        }
            public WorkParcel GetParcel()
            {
                EnsureNotOnThread(); // Only the background thread can get a parcel

                lock (_disposeLock)
                {
                    if (_disposed)
                    {
                        return(WorkParcel.Empty);
                    }
                }

                try
                {
                    _hasParcel?.Wait(_cancelSource.Token);
                }
                catch (Exception)
                {
                    // Swallow any exceptions caused by waiting on the parcel to avoid crashing VS.
                }

                lock (_disposeLock)
                {
                    if (_disposed)
                    {
                        return(WorkParcel.Empty);
                    }

                    try
                    {
                        _hasParcel.Reset();
                    }
                    catch (Exception)
                    {
                        // Swallow any exceptions caused by resetting the parcel switch to avoid crashing VS.
                    }

                    lock (_stateLock)
                    {
                        // Create a cancellation source for this parcel
                        _currentParcelCancelSource = new CancellationTokenSource();

                        var changes = _changes;
                        _changes = new List <ChangeReference>();
                        return(new WorkParcel(changes, _currentParcelCancelSource.Token));
                    }
                }
            }
        public static void RunManualResetEventSlimTest1_SimpleWait()
        {
            ManualResetEventSlim ev1 = new ManualResetEventSlim(false);
            ManualResetEventSlim ev2 = new ManualResetEventSlim(false);
            ManualResetEventSlim ev3 = new ManualResetEventSlim(false);

            Task.Run(delegate
            {
                ev2.Set();
                ev1.Wait();
                ev3.Set();
            });

            ev2.Wait();
            //Thread.Sleep(100);
            ev1.Set();
            ev3.Wait();
        }
Example #11
0
 /// <summary>
 /// Blocks the calling thread until the server starts or fails to start within the allotted timeout period.
 /// </summary>
 /// <param name="msTimeout">The number of milliseconds to wait before a timeout occurs.</param>
 /// <returns>True if the server starts within the specified timeout period, otherwise False.</returns>
 public bool WaitForIsListening(int msTimeout = 10000)
 {
     //return TimeoutFunc<bool>.Create(msTimeout, ct =>
     //{
     //    var result = false;
     //    while (!ct.IsCancellationRequested)
     //    {
     //        if (_mreIsListening != null)
     //        {
     //            result = _mreIsListening.WaitOne(1);
     //            if (result)
     //                break;
     //        }
     //        System.Threading.Thread.Sleep(1);
     //    }
     //    return result;
     //}).Start();
     return(_mreIsListening?.Wait(msTimeout) ?? false);
 }
        private void Dispose(bool disposing)
        {
            ReleaseUnmanagedResources();
            if (!disposing)
            {
                return;
            }

            _processingThreadCancel?.Cancel();
            _threadEndEvent?.Wait();
            _threadEndEvent?.Dispose();
            _processingThreadCancel?.Dispose();
            _queueCount?.Dispose();
            _poolCount?.Dispose();

            if (_handle.IsAllocated)
            {
                _handle.Free();
            }
        }
Example #13
0
        /// <summary>
        /// Waits for a response from the server.
        /// </summary>
        /// <returns>A Task which returns a CallResult&lt;TResponseType&gt;</returns>
        public async Task <RPCResult <TResponseType> > WaitForResponse <TResponseType>()
        {
            var result = await Task.Run(() =>
            {
                Exception ex = null;
                try
                {
                    _mreResponseReceived?.Wait();
                    return(GetResult <TResponseType>(Message.Response, Message.Exception));
                }
                catch (NullReferenceException) { ex = new ObjectDisposedException("CallHandler", "The CallHandler has been disposed.  The response cannot be trusted."); } //ignore this because someone called Dispose()
                catch (ObjectDisposedException) { ex = new ObjectDisposedException("CallHandler", "The CallHandler has been disposed.  The response cannot be trusted."); }    //ignore this because someone called Dispose()
                catch (TaskCanceledException)
                {
                    System.Diagnostics.Debugger.Break();
                }
                return(GetResult <TResponseType>(null, ex));
            });

            return(result);
        }
Example #14
0
        }         // func SendKillCommand

        public void StopProcess()
        {
            const string csSendKillCommand = "SendKillCommand";

            try
            {
                var isCommandSended = SendKillCommand();

                // Has the script a kill implementation
                if (!isCommandSended)
                {
                    var sendKillCommand = this[csSendKillCommand];
                    if (sendKillCommand != null)
                    {
                        isCommandSended = (bool)Lua.RtConvertValue(CallMemberDirect(csSendKillCommand, LuaResult.Empty.Values, throwExceptions: false), typeof(bool));
                    }
                }

                //// Ctrl+C - muss via CreateRemoteThread ausgeführt werden!
                //if (!lCommandSended)
                //{
                //	NativeMethods.GenerateConsoleCtrlEvent(0, process.Id);
                //	lCommandSended = true;
                //}

                // Wait for exist, and kill.
                var waitForExitTimeout = isCommandSended ? ConfigNode.GetAttribute <int>("exitTimeout") : 100;
                if (!process.WaitForExit(waitForExitTimeout))
                {
                    Log.LogMsg(LogMsgType.Warning, "Prozess wird abgeschossen.");
                    process.Kill();
                }

                waitForExitEvent?.Wait(waitForExitTimeout * 2);
            }
            catch (Exception e)
            {
                Log.Except(e);
            }
        }         // proc StopProcess
Example #15
0
        private WebResponse CreateResponse()
        {
            if (_writePending || _writing)
            {
                lock (this)
                {
                    if (_writePending || _writing)
                    {
                        _blockReaderUntilRequestStreamDisposed = new ManualResetEventSlim();
                    }
                }
            }
            _blockReaderUntilRequestStreamDisposed?.Wait();

            try
            {
                return(_response ?? (_response = new FileWebResponse(this, _uri, _fileAccess, !_syncHint)));
            }
            catch (Exception e)
            {
                throw new WebException(e.Message, e);
            }
        }
        public static void CancelAfterWait()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            ManualResetEventSlim mres = new ManualResetEventSlim();

            Task.Run(
                () =>
                {
                    for (int i = 0; i < 400; i++) ;
                    cancellationTokenSource.Cancel();
                }
                );

            //Now wait.. the wait should abort and an exception should be thrown
            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(cancellationToken), cancellationToken,
               "CancelBeforeWait:  An OCE(null) should have been thrown that references the cancellationToken.");

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually
        }
 public void WaitForInitialization() => r_InitializationLock?.Wait();
Example #18
0
 /// <inheritdoc />
 public void Wait()
 {
     _event?.Wait();
 }
Example #19
0
 public void Snooze(int milliseconds)
 {
     s_Shutdown.Wait(milliseconds);
 }
Example #20
0
    private static bool TestSync()
    {
        const int RUN_TIME = 15000;
            const int SETUP_TIME = 20;
            const int CONSUM = 100;
            const int PRODUC = 100;
            const int QUEUE = 5;

            Thread[] consumthrs = new Thread[CONSUM];
            Thread[] producthrs = new Thread[PRODUC];

            int[] results = new int[PRODUC+1];
            int[] consumCounters = new int[CONSUM];
            int[] producCounters = new int[PRODUC];
            int[] interruptCounters = new int[CONSUM + PRODUC];
            int sentInterrupts = 0;

            ManualResetEventSlim startEvent = new ManualResetEventSlim(false);
            SynchronousQueue<int> sync = new SynchronousQueue<int>();

                for (int i = 0; i < PRODUC; i++)
                {
                    int tid = i;
                    producthrs[i] = new Thread(() =>
                    {

                        // Wait the start for all threads
                        startEvent.Wait();

                        int endTime = Environment.TickCount + RUN_TIME;
                        //do
                        //{
                            //do
                            //{
                                try
                                {
                                    sync.Put(tid+1 , tid+1);
                                    //break;
                                }
                                catch (ThreadInterruptedException)
                                {
                                    interruptCounters[tid]++;
                                }
                            //} while (true);
                            //Thread.Yield();
                        ++producCounters[tid];
                            //if ((++producCounters[tid] % 1000) == 0)
                            //{
                                Console.Write("[#p{0}]", tid);
                            //}
                        //} while (Environment.TickCount < endTime);
                        try
                        {
                            Thread.Sleep(0);
                        }
                        catch (ThreadInterruptedException)
                        {
                            interruptCounters[tid]++;
                        }
                    });
                    producthrs[i].Start();
                }

                for (int i = 0; i < CONSUM; i++)
                {
                    int tid = i;
                    consumthrs[i] = new Thread(() =>
                    {

                        // Wait the start for all threads
                        startEvent.Wait();

                        int endTime = Environment.TickCount + RUN_TIME;
                        //do
                        //{
                            //do
                            //{
                                try
                                {
                                    int result =  sync.Take(tid + 1);
                                    //if (result != 0)
                                    //{
                                        results[result] += 1;
                                    //}

                                    //break;
                                }
                                catch (ThreadInterruptedException)
                                {
                                    interruptCounters[tid + CONSUM]++;
                                }
                            //} while (true);
                            //Thread.Yield();
                        ++consumCounters[tid];
                            //if ((++consumCounters[tid] % 1000) == 0)
                            //{
                                Console.Write("[#c{0}]", tid);
                            //}
                        //} while (Environment.TickCount < endTime);
                        try
                        {
                            Thread.Sleep(0);
                        }
                        catch (ThreadInterruptedException)
                        {
                            interruptCounters[tid + CONSUM]++;
                        }
                    });
                    consumthrs[i].Start();
                }

                Thread.Sleep(SETUP_TIME);
                startEvent.Set();

                // Wait until all threads have been terminated.
                for (int i = 0; i < CONSUM + PRODUC; i++)
                {
                    if (i < CONSUM)
                        consumthrs[i].Join();
                    else
                        producthrs[i - CONSUM].Join();
                }

                // Show results
                Console.WriteLine("\nConsumers counters:");
                for (int i = 0; i < CONSUM; i++)
                {
                    if ((i % 5) == 0)
                        Console.WriteLine();
                    Console.Write("[#c{0}: {1,4}]", i, consumCounters[i]);
                }

                Console.WriteLine("\nProducers counters:");
                for (int i = 0; i < PRODUC; i++)
                {
                    if ((i % 5) == 0)
                        Console.WriteLine();
                    Console.Write("[#p{0}: {1,4}", i, producCounters[i]);
                }
                Console.WriteLine("\ninterrupt counters:");
                int sum = 0;
                for (int i = 0; i < CONSUM + PRODUC; i++)
                {
                    sum += interruptCounters[i];
                    if ((i % 5) == 0)
                        Console.WriteLine();
                    Console.Write("[#{0}: {1,4}]", i, interruptCounters[i]);
                }
                Console.WriteLine("\nsent interrupts: {0}, received: {1}", sentInterrupts, sum);

                for (int i = 1; i < results.Count(); i++)
                {
                    if (results[i] == 0)
                        return false;
                    Console.WriteLine(i);
                }

            return true;
    }
        protected override Task <decimal> InvokeTestMethodAsync(ExceptionAggregator aggregator)
        {
            SharedData.ExecutingTest(TestMethod);

            DispatcherSynchronizationContext synchronizationContext = null;
            Dispatcher dispatcher = null;
            Thread     staThread;

            using (var staThreadStartedEvent = new ManualResetEventSlim(initialState: false))
            {
                staThread = new Thread((ThreadStart)(() =>
                {
                    // All WPF Tests need a DispatcherSynchronizationContext and we dont want to block pending keyboard
                    // or mouse input from the user. So use background priority which is a single level below user input.
                    synchronizationContext = new DispatcherSynchronizationContext();
                    dispatcher = Dispatcher.CurrentDispatcher;

                    // xUnit creates its own synchronization context and wraps any existing context so that messages are
                    // still pumped as necessary. So we are safe setting it here, where we are not safe setting it in test.
                    SynchronizationContext.SetSynchronizationContext(synchronizationContext);

                    staThreadStartedEvent.Set();

                    Dispatcher.Run();
                }));

                staThread.Name = $"{nameof(WpfTestRunner)} {TestMethod.Name}";
                staThread.SetApartmentState(ApartmentState.STA);
                staThread.Start();

                staThreadStartedEvent.Wait();
                Debug.Assert(synchronizationContext != null);
            }

            var taskScheduler = new SynchronizationContextTaskScheduler(synchronizationContext);
            var task          = Task.Factory.StartNew(async() =>
            {
                Debug.Assert(SynchronizationContext.Current is DispatcherSynchronizationContext);

                using (await SharedData.TestSerializationGate.DisposableWaitAsync(CancellationToken.None))
                {
                    // Sync up FTAO to the context that we are creating here.
                    ForegroundThreadAffinitizedObject.CurrentForegroundThreadData = new ForegroundThreadData(
                        Thread.CurrentThread,
                        new SynchronizationContextTaskScheduler(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher, DispatcherPriority.Background)),
                        ForegroundThreadDataKind.StaUnitTest);

                    // Reset our flag ensuring that part of this test actually needs WpfFact
                    s_wpfFactRequirementReason = null;

                    // Just call back into the normal xUnit dispatch process now that we are on an STA Thread with no synchronization context.
                    var invoker = new XunitTestInvoker(Test, MessageBus, TestClass, ConstructorArguments, TestMethod, TestMethodArguments, BeforeAfterAttributes, aggregator, CancellationTokenSource);
                    return(await invoker.RunAsync());
                }
            }, CancellationTokenSource.Token, TaskCreationOptions.None, taskScheduler).Unwrap();

            return(Task.Run(
                       async() =>
            {
                try
                {
                    return await task.ConfigureAwait(false);
                }
                finally
                {
                    // Make sure to shut down the dispatcher. Certain framework types listed for the dispatcher
                    // shutdown to perform cleanup actions. In the absence of an explicit shutdown, these actions
                    // are delayed and run during AppDomain or process shutdown, where they can lead to crashes of
                    // the test process.
                    dispatcher.InvokeShutdown();

                    // Join the STA thread, which ensures shutdown is complete.
                    staThread.Join(HangMitigatingTimeout);
                }
            }));
        }
Example #22
0
        public PythonEditor(
            string content = null,
            PythonLanguageVersion version = PythonLanguageVersion.V27,
            MockVs vs = null,
            IPythonInterpreterFactory factory = null,
            VsProjectAnalyzer analyzer        = null,
            string filename     = null,
            bool?inProcAnalyzer = null
            )
        {
            if (vs == null)
            {
                _disposeVS = true;
                vs         = new MockVs();
            }
            MockVsTextView view = null;

            try {
                AdvancedEditorOptions advancedOptions = null;
                vs.InvokeSync(() => {
                    advancedOptions = vs.GetPyService().AdvancedOptions;
                    advancedOptions.AutoListMembers     = true;
                    advancedOptions.AutoListIdentifiers = false;
                });
                AdvancedOptions = advancedOptions;

                if (factory == null)
                {
                    vs.InvokeSync(() => {
                        factory = vs.ComponentModel.GetService <IInterpreterRegistryService>()
                                  .Interpreters
                                  .FirstOrDefault(c => c.GetLanguageVersion() == version && c.Configuration.Id.StartsWith("Global|PythonCore"));
                        if (factory != null)
                        {
                            Console.WriteLine($"Using interpreter {factory.Configuration.InterpreterPath}");
                        }
                    });
                    if (factory == null)
                    {
                        _disposeFactory = true;
                        factory         = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version.ToVersion());
                        Console.WriteLine("Using analysis-only interpreter");
                    }
                }
                if (analyzer == null)
                {
                    _disposeAnalyzer = true;
                    analyzer         = vs.InvokeTask(() => VsProjectAnalyzer.CreateForTestsAsync(vs.ComponentModel.GetService <PythonEditorServices>(), factory, inProcAnalyzer ?? Debugger.IsAttached), 10000);
                }
                if (string.IsNullOrEmpty(filename))
                {
                    do
                    {
                        filename = PathUtils.GetAbsoluteFilePath(TestData.GetTempPath(), Path.GetRandomFileName()) + ".py";
                    } while (File.Exists(filename));
                }

                var cancel = CancellationTokens.After60s;
                using (var mre = new ManualResetEventSlim()) {
                    view = vs.CreateTextView(PythonCoreConstants.ContentType, content ?? "",
                                             v => {
                        v.TextView.TextBuffer.Properties[BufferParser.ParseImmediately]             = true;
                        v.TextView.TextBuffer.Properties[IntellisenseController.SuppressErrorLists] = IntellisenseController.SuppressErrorLists;
                        v.TextView.TextBuffer.Properties[VsProjectAnalyzer._testAnalyzer]           = analyzer;
                        v.TextView.TextBuffer.Properties[VsProjectAnalyzer._testFilename]           = filename;
                    },
                                             filename);

                    var entry = analyzer.GetAnalysisEntryFromPath(filename);
                    while (entry == null && !cancel.IsCancellationRequested)
                    {
                        Thread.Sleep(50);
                        entry = analyzer.GetAnalysisEntryFromPath(filename);
                    }

                    if (!string.IsNullOrEmpty(content) && !cancel.IsCancellationRequested && !entry.IsAnalyzed)
                    {
                        EventHandler evt = (s, e) => mre.SetIfNotDisposed();

                        try {
                            entry.AnalysisComplete += evt;
                            while (!mre.Wait(50, cancel) && !vs.HasPendingException && !entry.IsAnalyzed)
                            {
                                if (!analyzer.IsAnalyzing && !entry.IsAnalyzed)
                                {
                                    var bp = entry.TryGetBufferParser();
                                    Assert.IsNotNull(bp, "No buffer parser was ever created");
                                    var bi = PythonTextBufferInfo.TryGetForBuffer(view.TextView.TextBuffer);
                                    Assert.IsNotNull(bi, "No BufferInfo was ever created");
                                    bi.LastSentSnapshot = null;
                                    bp.EnsureCodeSyncedAsync(view.TextView.TextBuffer).WaitAndUnwrapExceptions();
                                }
                            }
                        } catch (OperationCanceledException) {
                        } finally {
                            entry.AnalysisComplete -= evt;
                        }
                    }
                    if (cancel.IsCancellationRequested)
                    {
                        Assert.Fail("Timed out waiting for code analysis");
                    }

                    vs.ThrowPendingException();
                }

                View     = view;
                view     = null;
                Analyzer = analyzer;
                analyzer = null;
                Factory  = factory;
                factory  = null;
                VS       = vs;
                vs       = null;
            } finally {
                if (view != null)
                {
                    view.Dispose();
                }
                if (analyzer != null && _disposeAnalyzer)
                {
                    analyzer.Dispose();
                }
                if (factory != null && _disposeFactory)
                {
                    var disp = factory as IDisposable;
                    if (disp != null)
                    {
                        disp.Dispose();
                    }
                }
                if (vs != null && _disposeVS)
                {
                    vs.Dispose();
                }
            }
        }
        public IEnumerator InterleavedMediaAndData()
        {
            // Create the peer connections
            var pc1_go = new GameObject("pc1");

            pc1_go.SetActive(false); // prevent auto-activation of components
            var pc1 = pc1_go.AddComponent <PeerConnection>();

            pc1.AutoInitializeOnStart = false;
            var pc2_go = new GameObject("pc2");

            pc2_go.SetActive(false); // prevent auto-activation of components
            var pc2 = pc2_go.AddComponent <PeerConnection>();

            pc2.AutoInitializeOnStart = false;

            // Batch changes manually
            pc1.AutoCreateOfferOnRenegotiationNeeded = false;
            pc2.AutoCreateOfferOnRenegotiationNeeded = false;

            // Create the signaler
            var sig_go = new GameObject("signaler");
            var sig    = sig_go.AddComponent <LocalOnlySignaler>();

            sig.Peer1 = pc1;
            sig.Peer2 = pc2;

            // Create the sender video source
            var source1 = pc1_go.AddComponent <UniformColorVideoSource>();
            //sender1.SenderTrackName = "track_name";
            MediaLine ml1 = pc1.AddMediaLine(MediaKind.Video);

            Assert.IsNotNull(ml1);
            ml1.Source = source1;

            // Create the receiver video source
            var       receiver2 = pc2_go.AddComponent <VideoReceiver>();
            MediaLine ml2       = pc2.AddMediaLine(MediaKind.Video);

            Assert.IsNotNull(ml2);
            ml2.Receiver = receiver2;

            // Activate
            pc1_go.SetActive(true);
            pc2_go.SetActive(true);

            // Initialize
            var initializedEvent1 = new ManualResetEventSlim(initialState: false);

            pc1.OnInitialized.AddListener(() => initializedEvent1.Set());
            Assert.IsNull(pc1.Peer);
            bool finishedInitializeBeforeTimeout1 = pc1.InitializeAsync().Wait(millisecondsTimeout: 50000);

            Assert.IsTrue(finishedInitializeBeforeTimeout1);
            var initializedEvent2 = new ManualResetEventSlim(initialState: false);

            pc2.OnInitialized.AddListener(() => initializedEvent2.Set());
            Assert.IsNull(pc2.Peer);
            bool finishedInitializeBeforeTimeout2 = pc2.InitializeAsync().Wait(millisecondsTimeout: 50000);

            Assert.IsTrue(finishedInitializeBeforeTimeout2);

            // Wait a frame so that the Unity event OnInitialized can propagate
            yield return(null);

            // Check the event was raised and the C# peer objects created
            Assert.IsTrue(initializedEvent1.Wait(millisecondsTimeout: 50000));
            Assert.IsNotNull(pc1.Peer);
            Assert.IsTrue(initializedEvent2.Wait(millisecondsTimeout: 50000));
            Assert.IsNotNull(pc2.Peer);

            // Confirm the source is ready, and there is a sender track.
            Assert.IsTrue(source1.IsLive);
            Assert.IsNotNull(ml1.SenderTrack);

            // Create some dummy out-of-band data channel to force SCTP negotiation
            // during the first offer, and be able to add some in-band data channels
            // later via subsequent SDP session negotiations.
            {
                Task <DataChannel> t1 = pc1.Peer.AddDataChannelAsync(42, "dummy", ordered: true, reliable: true);
                Task <DataChannel> t2 = pc2.Peer.AddDataChannelAsync(42, "dummy", ordered: true, reliable: true);
                Assert.IsTrue(t1.Wait(millisecondsTimeout: 10000));
                Assert.IsTrue(t2.Wait(millisecondsTimeout: 10000));
            }

            // Connect
            Assert.IsTrue(sig.StartConnection());
            yield return(sig.WaitForConnection(millisecondsTimeout: 60000));

            Assert.IsTrue(sig.IsConnected);

            // Wait a frame so that the Unity events for streams started can propagate
            yield return(null);

            // Check transceiver update
            var video_tr1 = ml1.Transceiver;

            Assert.IsNotNull(video_tr1);
            var video_tr2 = ml2.Transceiver;

            Assert.IsNotNull(video_tr2);
            Assert.AreEqual(0, video_tr1.MlineIndex);
            Assert.AreEqual(0, video_tr2.MlineIndex);

            // ====== Add in-band data channel ====================================

            // Add an in-band data channel on peer #1
            DataChannel dc1;
            {
                Task <DataChannel> t1 = pc1.Peer.AddDataChannelAsync("test_data_channel", ordered: true, reliable: true);
                Assert.IsTrue(t1.Wait(millisecondsTimeout: 10000));
                dc1 = t1.Result;
            }

            // Prepare to receive a new data channel on peer #2
            DataChannel dc2          = null;
            var         dc2_added_ev = new ManualResetEventSlim(initialState: false);

            pc2.Peer.DataChannelAdded += (DataChannel channel) => { dc2 = channel; dc2_added_ev.Set(); };

            // Renegotiate; data channel will consume media line #1
            Assert.IsTrue(sig.StartConnection());
            yield return(sig.WaitForConnection(millisecondsTimeout: 60000));

            Assert.IsTrue(sig.IsConnected);

            // Do not assume that connecting is enough to get the data channel, as callbacks are
            // asynchronously invoked. Instead explicitly wait for the created event to be raised.
            Assert.IsTrue(dc2_added_ev.Wait(millisecondsTimeout: 10000));

            // Check the data channel is ready
            Assert.IsNotNull(dc2);
            Assert.AreEqual(dc1.ID, dc2.ID);
            Assert.AreEqual(DataChannel.ChannelState.Open, dc1.State);
            Assert.AreEqual(DataChannel.ChannelState.Open, dc2.State);

            // ====== Add an extra media transceiver ==============================

            // Create the receiver video source
            var       receiver1b = pc1_go.AddComponent <VideoReceiver>();
            MediaLine ml1b       = pc1.AddMediaLine(MediaKind.Video);

            Assert.IsNotNull(ml1b);
            ml1b.Receiver = receiver1b;

            // Create the sender video source
            var source2b = pc2_go.AddComponent <UniformColorVideoSource>();
            //sender2b.SenderTrackName = "track_name_2";
            MediaLine ml2b = pc2.AddMediaLine(MediaKind.Video);

            Assert.IsNotNull(ml2b);
            ml2b.Source = source2b;

            // Renegotiate
            Assert.IsTrue(sig.StartConnection());
            yield return(sig.WaitForConnection(millisecondsTimeout: 60000));

            Assert.IsTrue(sig.IsConnected);

            // Wait a frame so that the Unity events for streams started can propagate
            yield return(null);

            // Check transceiver update
            var video_tr1b = ml1b.Transceiver;

            Assert.IsNotNull(video_tr1b);
            var video_tr2b = ml2b.Transceiver;

            Assert.IsNotNull(video_tr2b);
            Assert.AreEqual(2, video_tr1b.MlineIndex);
            Assert.AreEqual(2, video_tr2b.MlineIndex);
        }
Example #24
0
        void RACWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            ulong deltaTimeInQueue;

            string threadName = "RossiAlphaAnalyzer_" + rossiAlphaGateWidth;

            Thread.CurrentThread.Name = threadName;

#if USE_SPINTIME
            spinTimeReady = false;
#endif

            while (keepRunning == true)
            {
                isReadyToAnalyze = true;

#if USE_SPINTIME
                if (spinTimeReady)
                {
                    StartSpinCount();
                }
#endif

                waitingForMessage.Wait();  //wait for some other thread to place neutron data in this object and signal this worker to analyze

#if USE_SPINTIME
                if (spinTimeReady)
                {
                    EndSpinCount();
                }
                else
                {
                    spinTimeReady = true;
                }
#endif

                if (keepRunning == true)
                {
                    int   i, j;
                    ulong eventTime;
                    uint  eventNeutrons;
                    uint  eventNumNeutrons;
                    RossiAlphaCircularNeutronEvent anEvent;
                    RossiAlphaCircularNeutronEvent nextEvent;

                    for (j = 0; j < numEventsThisBlock; j++)
                    {
                        eventTime        = inputEventTime[j];
                        eventNeutrons    = inputEventNeutrons[j];
                        eventNumNeutrons = inputEventNumNeutrons[j];

                        //fill in these new data at the tail of the circular linked list,
                        //remembering that endOfNeutronEventList points to the next EMPTY struct in the list
                        //INCLUDING at the beginning when the head and tail point to the same struct
                        endOfList.FillEventWithData(eventTime, eventNeutrons, eventNumNeutrons);

                        //check to see if the circular list will overflow
                        if (endOfList.next.serialNumber == startOfList.serialNumber)
                        {
                            //if stack would overflow, add RawAnalysisProperties.circularListBlockIncrement neutron events at this spot in the stack...
                            anEvent   = endOfList;
                            nextEvent = endOfList.next;
                            for (i = 0; i < RawAnalysisProperties.circularListBlockIncrement; i++)
                            {
                                anEvent.next = new RossiAlphaCircularNeutronEvent(i + numObjectsInCircularLinkedList);
                                anEvent      = anEvent.next;
                            }
                            anEvent.next = nextEvent;                                                           //patch the circular linked list back together
                            numObjectsInCircularLinkedList += RawAnalysisProperties.circularListBlockIncrement; //increase the record of the number of structs in the circular list
                        }

                        //move endOfNeutronEventList to the next empty struct
                        endOfList = endOfList.next;

                        //for fun, count how many times we have lapped the circular list in this experiment
                        if (endOfList.serialNumber == 0)
                        {
                            numCircuits++;
                        }

                        //see if oldest event in the queue is expiring,
                        //and while there are expiring events calculate the RossiAlpha statistics for those events
                        deltaTimeInQueue = eventTime - startOfList.eventTime;
                        while (deltaTimeInQueue > rossiAlphaWindowWidth)
                        {
                            //record the time of the expiring gate from the startOfList event, the total measured time for this experiment
                            totalRossiAlphaAnalysisTime = startOfList.eventTime + rossiAlphaWindowWidth;

                            //do RossiAlpha analysis here, accumulating statistics
                            //add up how many neutrons there were in each RossiAlpha gate from the time of the expiring event
                            int   whichBin;
                            ulong deltaTime;

                            //skip the event at the head of the list.
                            //To match data from the legacy code, start with the neutron event following this expiring head event.
                            anEvent = startOfList.next;
                            while (anEvent.serialNumber != endOfList.serialNumber)  //...that is, until we reach the end of the list...
                            {
                                //Find the lowest bin with end time greater than the time of anEvent.
                                deltaTime = anEvent.eventTime - startOfList.eventTime;
                                whichBin  = (int)(Math.Ceiling((double)deltaTime / (double)rossiAlphaGateWidth) + 0.1);

                                if (whichBin < RawAnalysisProperties.numRAGatesPerWindow)  //then this event falls into a bin; add this event's neutrons to that bin
                                {
                                    neutronsPerRossiAlphaGate[whichBin] += anEvent.numNeutrons;
                                    //go to the next event
                                    anEvent = anEvent.next;
                                }
                                else
                                {
                                    anEvent = endOfList;  //abort the loop by going to the end of the list
                                }
                            }

                            //remove expiring oldest event from the stack
                            startOfList = startOfList.next;

                            //re-calculate the delta time in the stack
                            deltaTimeInQueue = eventTime - startOfList.eventTime;
                        } //END of handling an individual NeutronEvent
                    }     //END of handling this block of events

                    //prepare this thread's wait condition so will wait for a message
                    //before telling master thread this thread's analysis is complete
                    waitingForMessage.Reset();
                }  //END of if(keepRunning)
                else
                {
                    //The master thread has cleared the keepRunning flag, so this worker is exiting
                    //Do any cleanup etc. here.
                }
            }  //END of while(keepRunning)
        }
Example #25
0
        public static void OnCompleted_CompletesInAnotherTaskScheduler(bool generic, bool? continueOnCapturedContext)
        {
            SynchronizationContext origCtx = SynchronizationContext.Current;
            try
            {
                SynchronizationContext.SetSynchronizationContext(null); // get off xunit's SynchronizationContext to avoid interactions with await

                var quwi = new QUWITaskScheduler();
                RunWithSchedulerAsCurrent(quwi, delegate
                {
                    Assert.True(TaskScheduler.Current == quwi, "Expected to be on target scheduler");

                    // Create the not completed task and get its awaiter
                    var mres = new ManualResetEventSlim();
                    var tcs = new TaskCompletionSource<object>();

                    // Hook up the callback
                    bool ranOnScheduler = false;
                    Action callback = () =>
                    {
                        ranOnScheduler = (TaskScheduler.Current == quwi);
                        mres.Set();
                    };
                    if (generic)
                    {
                        if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                        else tcs.Task.GetAwaiter().OnCompleted(callback);
                    }
                    else
                    {
                        if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                        else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
                    }
                    Assert.False(mres.IsSet, "Callback should not yet have run.");

                    // Complete the task in another scheduler and wait for the callback to run
                    Task.Run(delegate { tcs.SetResult(null); });
                    mres.Wait();

                    // Validate the callback ran on the right scheduler
                    bool shouldHaveRunOnScheduler = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
                    Assert.Equal(shouldHaveRunOnScheduler, ranOnScheduler);
                });
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(origCtx);
            }
        }
Example #26
0
		void ParticipateUntil (ManualResetEventSlim evt, int millisecondsTimeout)
		{
			evt.Wait (millisecondsTimeout);
		}
Example #27
0
        public void ExecuteAllMethodCallUpdateAllPackageOnAllProjects(bool includePrerelease)
        {
            // Arrange
            var packageA  = PackageUtility.CreatePackage("A", "1.0");
            var packageB  = PackageUtility.CreatePackage("B", "2.0");
            var packageC  = PackageUtility.CreatePackage("C", "3.0");
            var packageB2 = PackageUtility.CreatePackage("B", "4.0");

            var sourceRepository = new MockPackageRepository();

            sourceRepository.AddPackage(packageA);
            sourceRepository.AddPackage(packageC);
            sourceRepository.AddPackage(packageB);
            sourceRepository.AddPackage(packageB2);

            var localRepository = new MockPackageRepository();

            localRepository.AddPackage(packageB);

            var projectManager1 = new Mock <IProjectManager>();

            projectManager1.Setup(p => p.LocalRepository).Returns(localRepository);

            var projectManager2 = new Mock <IProjectManager>();

            projectManager2.Setup(p => p.LocalRepository).Returns(localRepository);

            var project1 = MockProjectUtility.CreateMockProject("Project1");
            var project2 = MockProjectUtility.CreateMockProject("Project2");

            var packageManager = new Mock <IVsPackageManager>();

            packageManager.Setup(p => p.SourceRepository).Returns(sourceRepository);
            packageManager.Setup(p => p.GetProjectManager(It.Is <Project>(s => s == project1))).Returns(projectManager1.Object);
            packageManager.Setup(p => p.GetProjectManager(It.Is <Project>(s => s == project2))).Returns(projectManager2.Object);
            packageManager.Setup(p => p.IsProjectLevel(It.IsAny <IPackage>())).Returns(true);

            var solutionManager = new Mock <ISolutionManager>();

            solutionManager.Setup(p => p.GetProject(It.Is <string>(s => s == "Project1"))).Returns(project1);
            solutionManager.Setup(p => p.GetProject(It.Is <string>(s => s == "Project2"))).Returns(project2);
            solutionManager.Setup(p => p.GetProjects()).Returns(new Project[] { project1, project2 });

            var mockWindowService = new Mock <IUserNotifierServices>();

            mockWindowService.Setup(p => p.ShowProjectSelectorWindow(
                                        It.IsAny <string>(),
                                        It.IsAny <IPackage>(),
                                        It.IsAny <Predicate <Project> >(),
                                        It.IsAny <Predicate <Project> >())).Returns(new Project[] { project1, project2 });

            var provider = CreateSolutionUpdatesProvider(packageManager.Object, localRepository, solutionManager: solutionManager.Object, userNotifierServices: mockWindowService.Object);

            provider.IncludePrerelease = includePrerelease;
            var extensionTree = provider.ExtensionsTree;
            var extensionB2   = new PackageItem(provider, packageB2);

            var firstTreeNode = (SimpleTreeNode)extensionTree.Nodes[0];

            firstTreeNode.Repository.AddPackage(packageA);
            firstTreeNode.Repository.AddPackage(packageB);
            firstTreeNode.Repository.AddPackage(packageC);
            firstTreeNode.Extensions.Add(extensionB2);

            provider.SelectedNode = firstTreeNode;
            IVsPackageManager        activePackageManager = provider.GetActivePackageManager();
            Mock <IVsPackageManager> mockPackageManager   = Mock.Get <IVsPackageManager>(activePackageManager);

            var       manualEvent = new ManualResetEventSlim(false);
            Exception exception   = null;

            provider.ExecuteCompletedCallback = delegate
            {
                try
                {
                    // Assert
                    Assert.Equal(RepositoryOperationNames.Update, sourceRepository.LastOperation);
                    mockPackageManager.Verify(
                        p => p.UpdatePackages(true, includePrerelease, provider, provider),
                        Times.Once());
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
                finally
                {
                    manualEvent.Set();
                }
            };

            // Act
            provider.Execute(item: null);

            // do not allow the method to return
            manualEvent.Wait();

            Assert.Null(exception);
        }
Example #28
0
        public void ExecuteMethodDoNotCallUpdatePackageIfNoProjectIsChecked()
        {
            // Arrange
            var packageA  = PackageUtility.CreatePackage("A", "1.0");
            var packageB  = PackageUtility.CreatePackage("B", "2.0");
            var packageC  = PackageUtility.CreatePackage("C", "3.0");
            var packageB2 = PackageUtility.CreatePackage("B", "4.0");

            var sourceRepository = new MockPackageRepository();

            sourceRepository.AddPackage(packageA);
            sourceRepository.AddPackage(packageC);
            sourceRepository.AddPackage(packageB);
            sourceRepository.AddPackage(packageB2);

            var localRepository = new MockPackageRepository();

            localRepository.AddPackage(packageB);

            var projectManager1 = new Mock <IProjectManager>();

            projectManager1.Setup(p => p.LocalRepository).Returns(localRepository);

            var projectManager2 = new Mock <IProjectManager>();

            projectManager2.Setup(p => p.LocalRepository).Returns(localRepository);

            var project1 = MockProjectUtility.CreateMockProject("Project1");
            var project2 = MockProjectUtility.CreateMockProject("Project2");

            var packageManager = new Mock <IVsPackageManager>();

            packageManager.Setup(p => p.SourceRepository).Returns(sourceRepository);
            packageManager.Setup(p => p.GetProjectManager(It.Is <Project>(s => s == project1))).Returns(projectManager1.Object);
            packageManager.Setup(p => p.GetProjectManager(It.Is <Project>(s => s == project2))).Returns(projectManager2.Object);
            packageManager.Setup(p => p.IsProjectLevel(It.IsAny <IPackage>())).Returns(true);

            var solutionManager = new Mock <ISolutionManager>();

            solutionManager.Setup(p => p.GetProject(It.Is <string>(s => s == "Project1"))).Returns(project1);
            solutionManager.Setup(p => p.GetProject(It.Is <string>(s => s == "Project2"))).Returns(project2);
            solutionManager.Setup(p => p.GetProjects()).Returns(new Project[] { project1, project2 });

            var mockWindowService = new Mock <IUserNotifierServices>();

            mockWindowService.Setup(p => p.ShowProjectSelectorWindow(
                                        It.IsAny <string>(),
                                        It.IsAny <IPackage>(),
                                        It.IsAny <Predicate <Project> >(),
                                        It.IsAny <Predicate <Project> >())).Returns(new Project[0]);

            var provider      = CreateSolutionUpdatesProvider(packageManager.Object, localRepository, solutionManager: solutionManager.Object, userNotifierServices: mockWindowService.Object);
            var extensionTree = provider.ExtensionsTree;

            var firstTreeNode = (SimpleTreeNode)extensionTree.Nodes[0];

            firstTreeNode.Repository.AddPackage(packageA);
            firstTreeNode.Repository.AddPackage(packageB);
            firstTreeNode.Repository.AddPackage(packageC);

            provider.SelectedNode = firstTreeNode;
            IVsPackageManager        activePackageManager = provider.GetActivePackageManager();
            Mock <IVsPackageManager> mockPackageManager   = Mock.Get <IVsPackageManager>(activePackageManager);

            var manualEvent = new ManualResetEventSlim(false);

            provider.ExecuteCompletedCallback = delegate
            {
                // Assert
                mockPackageManager.Verify(p => p.UpdatePackage(
                                              new Project[] { project1, project2 },
                                              packageB2,
                                              It.IsAny <IEnumerable <PackageOperation> >(),
                                              true,
                                              false,
                                              provider,
                                              provider), Times.Never());

                manualEvent.Set();
            };

            var extensionB2 = new PackageItem(provider, packageB2);

            // Act
            provider.Execute(extensionB2);

            // do not allow the method to return
            manualEvent.Wait();
        }
 /// <inheritdoc />
 public void Wait() => _event?.Wait();
Example #30
0
 public async Task ConfiguredAwaiter_ContinuesOnCapturedContext(bool continueOnCapturedContext)
 {
     await Task.Run(() =>
     {
         var tsc = new TrackingSynchronizationContext();
         SynchronizationContext.SetSynchronizationContext(tsc);
         try
         {
             ValueTask<int> t = 42;
             var mres = new ManualResetEventSlim();
             t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => mres.Set());
             Assert.True(mres.Wait(10000));
             Assert.Equal(continueOnCapturedContext ? 1 : 0, tsc.Posts);
         }
         finally
         {
             SynchronizationContext.SetSynchronizationContext(null);
         }
     });
 }
Example #31
0
        public Task TakeScreenshotAsync() => Task.Run(async() =>
        {
            Interlocked.Increment(ref screenShotTasks);

            if (!captureMenuCursor.Value)
            {
                cursorVisibility.Value = false;

                // We need to wait for at most 3 draw nodes to be drawn, following which we can be assured at least one DrawNode has been generated/drawn with the set value
                const int frames_to_wait = 3;

                int framesWaited = 0;

                using (var framesWaitedEvent = new ManualResetEventSlim(false))
                {
                    ScheduledDelegate waitDelegate = host.DrawThread.Scheduler.AddDelayed(() =>
                    {
                        if (framesWaited++ < frames_to_wait)
                        {
                            // ReSharper disable once AccessToDisposedClosure
                            framesWaitedEvent.Set();
                        }
                    }, 10, true);

                    framesWaitedEvent.Wait();
                    waitDelegate.Cancel();
                }
            }

            using (var image = await host.TakeScreenshotAsync())
            {
                if (Interlocked.Decrement(ref screenShotTasks) == 0 && cursorVisibility.Value == false)
                {
                    cursorVisibility.Value = true;
                }

                var fileName = getFileName();
                if (fileName == null)
                {
                    return;
                }

                var stream = storage.GetStream(fileName, FileAccess.Write);

                switch (screenshotFormat.Value)
                {
                case ScreenshotFormat.Png:
                    image.SaveAsPng(stream);
                    break;

                case ScreenshotFormat.Jpg:
                    image.SaveAsJpeg(stream);
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(screenshotFormat));
                }

                notificationOverlay.Post(new SimpleNotification
                {
                    Text      = $"{fileName} 已保存!",
                    Activated = () =>
                    {
                        storage.OpenInNativeExplorer();
                        return(true);
                    }
                });
            }
        });
Example #32
0
    public void ConcurrentReadersTest()
    {
        const int threadCount = 8;
        var threads = new Thread[threadCount];
        var exceptions = new Exception[threadCount];
        var locker = new object();
        var acquired = 0;
        var m2 = new ManualResetEventSlim(false);
        var m1 = new ManualResetEventSlim(false);

        for (var i = 0; i < threadCount; i++)
        {
            var ic = i; // capture
            threads[i] = new Thread(() =>
            {
                using (var scope = ScopeProvider.CreateScope())
                {
                    try
                    {
                        scope.EagerReadLock(Constants.Locks.Servers);
                        lock (locker)
                        {
                            acquired++;
                            if (acquired == threadCount)
                            {
                                m2.Set();
                            }
                        }

                        m1.Wait();
                        lock (locker)
                        {
                            acquired--;
                        }
                    }
                    catch (Exception e)
                    {
                        exceptions[ic] = e;
                    }

                    scope.Complete();
                }
            });
        }

        // ensure that current scope does not leak into starting threads
        using (ExecutionContext.SuppressFlow())
        {
            foreach (var thread in threads)
            {
                thread.Start();
            }
        }

        m2.Wait();
        // all threads have locked in parallel
        var maxAcquired = acquired;
        m1.Set();

        foreach (var thread in threads)
        {
            thread.Join();
        }

        Assert.AreEqual(threadCount, maxAcquired);
        Assert.AreEqual(0, acquired);

        for (var i = 0; i < threadCount; i++)
        {
            Assert.IsNull(exceptions[i]);
        }
    }
Example #33
0
        /// <summary>
        /// Update the pages in the texture loader that should be loaded. Note that if you are retiring indirection textures
        /// you can pass an enumerator to their ids so their removal will not be pooled.
        /// </summary>
        /// <param name="loopResumingCallback">An action that is fired just before the loop restarts to load images.</param>
        /// <param name="retiringIndirectionTextureIds">An enumerator over indirection texture ids that should not have removal pooled since they are being retired. Null means ignore this (default).</param>
        public void updatePagesFromRequests(Action loopResumingCallback = null, IEnumerable <byte> retiringIndirectionTextureIds = null)
        {
            //If there are no added pages or changes to indirection textures, there is nothing to do with this call, just return
            if (addedPages.Count == 0 && removedPages.Count == 0 && loopResumingCallback == null && retiringIndirectionTextureIds == null)
            {
                return;
            }

            //Finish any current image loading and wait until that is complete
            if (loadingTask != null)
            {
                stopLoading = true;
                loadingTask.Wait();
            }

            //Careful with order, we want to make sure the loadingtask is done before getting a lock again since that function locks for its duration.
            lock (syncObject)
            {
                //We have a lock now, are we still ok to load?
                if (cancelBackgroundLoad)
                {
                    throw new CancelThreadException();
                }
            }

            //If we have pages to retire, for extra safety wait until all outstanding staging buffers are finished uploading
            if (retiringIndirectionTextureIds != null)
            {
                foreach (var stagingBuffer in stagingBufferSets)
                {
                    stagingBuffer.waitForGpuUpload();
                }
            }

            //Reset
            stopLoading = false;

            //Remove pages
            foreach (var page in removedPages)
            {
                PTexPage pTexPage;
                if (usedPhysicalPages.TryGetValue(page, out pTexPage))
                {
                    //See if this page is part of a retired texture, if not pool the page
                    if (retiringIndirectionTextureIds == null || !retiringIndirectionTextureIds.Contains(pTexPage.VirtualTexturePage.indirectionTexId))
                    {
                        physicalPagePool.Add(page, pTexPage);
                    }
                    else
                    {
                        pTexPage.VirtualTexturePage = null;
                    }
                    physicalPageQueue.Add(pTexPage);
                    usedPhysicalPages.Remove(page);
                }
                else
                {
                    pagesToLoad.Remove(page);
                }
            }

            //Clear out any other physical page pool entries
            if (retiringIndirectionTextureIds != null)
            {
                List <PTexPage> currentPagePool = physicalPagePool.Values.ToList();
                foreach (var pooledPage in currentPagePool)
                {
                    if (retiringIndirectionTextureIds.Contains(pooledPage.VirtualTexturePage.indirectionTexId))
                    {
                        physicalPagePool.Remove(pooledPage.VirtualTexturePage);
                        pooledPage.VirtualTexturePage = null;
                    }
                }
            }

            //Process pages into loaded and not loaded
            foreach (var addedPage in addedPages)
            {
                PTexPage pTexPage;
                //Does the virtual texture already contain the page?
                if (physicalPagePool.TryGetValue(addedPage, out pTexPage))
                {
                    //Already contained, just update the queue and pool, this requires no texture updates
                    physicalPageQueue.Remove(pTexPage);
                    physicalPagePool.Remove(addedPage);
                    usedPhysicalPages.Add(addedPage, pTexPage);
                }
                else if (!usedPhysicalPages.ContainsKey(addedPage) && !pagesToLoad.Contains(addedPage)) //Add all new pages that are not already used, could potentailly be slow, can second check be replaced by a hash map
                {
                    pagesToLoad.Add(addedPage);
                }
            }

            if (loopResumingCallback != null)
            {
                loopResumingCallback.Invoke();
            }

            Overprevisioned = pagesToLoad.Count > physicalPageQueue.Count;

            //Start loading task again
            pagesToLoad.Sort((v1, v2) => ((v1.mip << 24) + indirectionTextureRequestCount[v1.indirectionTexId]) - ((v2.mip << 24) + indirectionTextureRequestCount[v2.indirectionTexId]));
            loadingTask = Task.Run(() =>
            {
                lock (syncObject)
                {
                    PerformanceMonitor.start("updatePagesFromRequests processing pages");
                    for (int i = pagesToLoad.Count - 1; i > -1; --i) //Process backwards, try to avoid as many collection element shifts as possible, this is sorted so the desired read order is reversed in actual memory
                    {
                        if (cancelBackgroundLoad)                    //Reaquired lock, are we still active
                        {
                            throw new CancelThreadException();
                        }
                        if (stopLoading)
                        {
                            break;
                        }
                        System.Threading.Monitor.Exit(syncObject);
                        stagingBufferWaitEvent.Wait();     //Make sure we actually can dequeue a staging buffer
                        StagingBufferSet stagingBuffers;
                        lock (stagingBufferSets)
                        {
                            stagingBuffers = this.stagingBufferSets[0];
                            stagingBuffers.reset();
                            stagingBufferSets.RemoveAt(0);
                            if (stagingBufferSets.Count == 0)
                            {
                                //We have no more staging buffers, force next iteration to wait until the last one has been returned.
                                stagingBufferWaitEvent.Reset();
                            }
                        }
                        System.Threading.Monitor.Enter(syncObject);
                        if (loadPage(pagesToLoad[i], stagingBuffers))
                        {
                            virtualTextureManager.syncToGpu(stagingBuffers);
                        }
                        else
                        {
                            returnStagingBuffer(stagingBuffers);
                        }
                        pagesToLoad.RemoveAt(i);
                    }
                    PerformanceMonitor.stop("updatePagesFromRequests processing pages");
                }
            });

            //Reset added and removed pages
            addedPages.Clear();
            removedPages.Clear();
        }
        public static void RunManualResetEventSlimTest5_Dispose_Negative()
        {
            ManualResetEventSlim mres = new ManualResetEventSlim(false);
            mres.Dispose();

            Assert.Throws<ObjectDisposedException>(() => mres.Reset());
            // Failure Case: The object has been disposed, should throw ObjectDisposedException.

            Assert.Throws<ObjectDisposedException>(() => mres.Wait(0));
            // Failure Case: The object has been disposed, should throw ObjectDisposedException.

            Assert.Throws<ObjectDisposedException>(
                () =>
                {
                    WaitHandle handle = mres.WaitHandle;
                });
            // Failure Case: The object has been disposed, should throw ObjectDisposedException.

            mres = new ManualResetEventSlim(false);

            ManualResetEvent mre = (ManualResetEvent)mres.WaitHandle;
            mres.Dispose();

            Assert.Throws<ObjectDisposedException>(() => mre.WaitOne(0));
            // Failure Case: The underlying event object has been disposed, should throw ObjectDisposedException.

        }
        public async Task TestOrdering_Sync_OrderedDisabled()
        {
            // If ordering were enabled, this test would hang.

            var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2, EnsureOrdered = false };

            var mres = new ManualResetEventSlim();
            var tb = new TransformBlock<int, int>(i =>
            {
                if (i == 0) mres.Wait();
                return i;
            }, options);
            tb.Post(0);
            tb.Post(1);

            Assert.Equal(1, await tb.ReceiveAsync());
            mres.Set();
            Assert.Equal(0, await tb.ReceiveAsync());

            tb.Complete();
            await tb.Completion;
        }
        public static void RunManualResetEventSlimTest6_Exceptions()
        {
            ManualResetEventSlim mres = null;
            Assert.Throws<ArgumentOutOfRangeException>(() => mres = new ManualResetEventSlim(false, -1));
            // Failure Case: Constructor didn't throw AORE when -1 passed

            mres = new ManualResetEventSlim(false);

            Assert.Throws<ArgumentOutOfRangeException>(() => mres.Wait(-2));
            // Failure Case: Wait(int) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => mres.Wait(TimeSpan.FromDays(-1)));
            // Failure Case: Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => mres.Wait(TimeSpan.MaxValue));
            // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max

            Assert.Throws<ArgumentOutOfRangeException>(() => mres.Wait(TimeSpan.FromDays(-1), new CancellationToken()));
            // Failure Case: Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => mres.Wait(TimeSpan.MaxValue, new CancellationToken()));
            // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max
        }
 /// <summary>
 /// Waits for the event to be completed
 /// </summary>
 public void Wait() => Event?.Wait();
Example #38
0
    public void Throws_When_Lock_Timeout_Is_Exceeded_Write()
    {
        var counter = 0;
        var gate = new ManualResetEventSlim(false);
        var logger = GetRequiredService<ILogger<LocksTests>>();

        using (ExecutionContext.SuppressFlow())
        {
            var t1 = Task.Run(() =>
            {
                using var scope = ScopeProvider.CreateScope();

                _ = scope.Database; // Begin transaction
                Interlocked.Increment(ref counter);
                gate.Wait();

                logger.LogInformation("t1 - Attempting to acquire write lock");
                Assert.DoesNotThrow(() =>
                {
                    // ReSharper disable once AccessToDisposedClosure
                    // This will acquire right away
                    scope.EagerWriteLock(TimeSpan.FromMilliseconds(1000), Constants.Locks.ContentTree);
                });

                logger.LogInformation("t1 - Acquired write lock, sleeping");
                Thread.Sleep(1500); // Wait longer than the Read Lock B timeout

                scope.Complete();
                logger.LogInformation("t1 -  Complete transaction");
            });

            var t2 = Task.Run(() =>
            {
                using var scope = ScopeProvider.CreateScope();

                _ = scope.Database; // Begin transaction
                Interlocked.Increment(ref counter);
                gate.Wait();
                Thread.Sleep(100); // Let other transaction obtain write lock first.

                logger.LogInformation("t2 - Attempting to acquire write lock");
                var ex = Assert.Throws<DistributedWriteLockTimeoutException>(() =>
                {
                    // ReSharper disable once AccessToDisposedClosure
                    scope.EagerWriteLock(TimeSpan.FromMilliseconds(1000), Constants.Locks.ContentTree);
                    logger.LogInformation("t2 - Acquired write lock, something has gone wrong.");
                });

                if (ex != null)
                {
                    logger.LogInformation("t2 - Failed to acquire write lock in time, all is well.");
                }

                scope.Complete();
            });

            while (counter < 2)
            {
                Thread.Sleep(10);
            }

            gate.Set();
            Task.WaitAll(t1, t2);
        }
    }
Example #39
0
                private void DrainQueue(CancellationToken token, ICancelable cancel)
                {
                    while (true)
                    {
                        try
                        {
                            _evt.Wait(token);
                        }
                        catch (OperationCanceledException)
                        {
                            return;
                        }

                        var hasFailed = false;
                        var error     = default(Exception);

                        var hasValue     = false;
                        var value        = default(TSource);
                        var hasCompleted = false;

                        var shouldWait = false;
                        var waitTime   = default(TimeSpan);

                        lock (_gate)
                        {
                            if (_hasFailed)
                            {
                                error     = _exception;
                                hasFailed = true;
                            }
                            else
                            {
                                var now = Elapsed;

                                if (_queue.Count > 0)
                                {
                                    var next = _queue.Dequeue();

                                    hasValue = true;
                                    value    = next.Value;

                                    var nextDue = next.Interval;
                                    if (nextDue.CompareTo(now) > 0)
                                    {
                                        shouldWait = true;
                                        waitTime   = Scheduler.Normalize(nextDue.Subtract(now));
                                    }
                                }
                                else if (_hasCompleted)
                                {
                                    hasCompleted = true;

                                    if (_completeAt.CompareTo(now) > 0)
                                    {
                                        shouldWait = true;
                                        waitTime   = Scheduler.Normalize(_completeAt.Subtract(now));
                                    }
                                }
                            }
                        } /* lock (_gate) */

                        if (shouldWait)
                        {
                            var timer = new ManualResetEventSlim();
                            _scheduler.ScheduleAction(timer, waitTime, static slimTimer => { slimTimer.Set(); });

                            try
                            {
                                timer.Wait(token);
                            }
                            catch (OperationCanceledException)
                            {
                                return;
                            }
                        }

                        if (hasValue)
                        {
                            ForwardOnNext(value !);
                        }
                        else
                        {
                            if (hasCompleted)
                            {
                                ForwardOnCompleted();
                            }
                            else if (hasFailed)
                            {
                                ForwardOnError(error !);
                            }

                            return;
                        }
                    }
                }
Example #40
0
    public void ConcurrentWritersTest()
    {
        const int threadCount = 8;
        var threads = new Thread[threadCount];
        var exceptions = new Exception[threadCount];
        var locker = new object();
        var acquired = 0;
        var entered = 0;
        var ms = new AutoResetEvent[threadCount];
        for (var i = 0; i < threadCount; i++)
        {
            ms[i] = new AutoResetEvent(false);
        }

        var m1 = new ManualResetEventSlim(false);

        for (var i = 0; i < threadCount; i++)
        {
            var ic = i; // capture
            threads[i] = new Thread(() =>
            {
                using (var scope = ScopeProvider.CreateScope())
                {
                    try
                    {
                        lock (locker)
                        {
                            entered++;
                            if (entered == threadCount)
                            {
                                m1.Set();
                            }
                        }

                        ms[ic].WaitOne();
                        scope.EagerWriteLock(Constants.Locks.Servers);
                        lock (locker)
                        {
                            acquired++;
                        }

                        ms[ic].WaitOne();
                        lock (locker)
                        {
                            acquired--;
                        }
                    }
                    catch (Exception e)
                    {
                        exceptions[ic] = e;
                    }

                    scope.Complete();
                }
            });
        }

        // ensure that current scope does not leak into starting threads
        using (ExecutionContext.SuppressFlow())
        {
            foreach (var thread in threads)
            {
                thread.Start();
            }
        }

        m1.Wait();
        // all threads have entered
        ms[0].Set(); // let 0 go
        // TODO: This timing is flaky
        Thread.Sleep(100);
        for (var i = 1; i < threadCount; i++)
        {
            ms[i].Set(); // let others go
        }

        // TODO: This timing is flaky
        Thread.Sleep(500);
        // only 1 thread has locked
        Assert.AreEqual(1, acquired);
        for (var i = 0; i < threadCount; i++)
        {
            ms[i].Set(); // let all go
        }

        foreach (var thread in threads)
        {
            thread.Join();
        }

        Assert.AreEqual(0, acquired);

        for (var i = 0; i < threadCount; i++)
        {
            Assert.IsNull(exceptions[i]);
        }
    }
Example #41
0
        public static void BaseSynchronizationContext_SameAsNoSynchronizationContext()
        {
            var quwi = new QUWITaskScheduler();
            SynchronizationContext origCtx = SynchronizationContext.Current;
            try
            {
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
                RunWithSchedulerAsCurrent(quwi, delegate
                {
                    ManualResetEventSlim mres = new ManualResetEventSlim();
                    var tcs = new TaskCompletionSource<object>();
                    var awaiter = ((Task)tcs.Task).GetAwaiter();

                    bool ranOnScheduler = false;
                    bool ranWithoutSyncCtx = false;
                    awaiter.OnCompleted(() =>
                    {
                        ranOnScheduler = (TaskScheduler.Current == quwi);
                        ranWithoutSyncCtx = SynchronizationContext.Current == null;
                        mres.Set();
                    });
                    Assert.False(mres.IsSet, "Callback should not yet have run.");

                    Task.Run(delegate { tcs.SetResult(null); });
                    mres.Wait();

                    Assert.True(ranOnScheduler, "Should have run on scheduler");
                    Assert.True(ranWithoutSyncCtx, "Should have run with a null sync ctx");
                });
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(origCtx);
            }
        }
Example #42
0
        public void ExecuteUninstallsSolutionLevelPackageWhenUpdating()
        {
            // Arrange
            var packageA_10 = PackageUtility.CreatePackage("A", "1.0", content: null, assemblyReferences: null, tools: new[] { "init.ps1" }, dependencies: null);
            var packageA_12 = PackageUtility.CreatePackage("A", "1.2", content: null, assemblyReferences: null, tools: new[] { "init.ps1" }, dependencies: null);

            var sourceRepository = new MockPackageRepository();

            sourceRepository.AddPackage(packageA_12);

            var localRepository = new MockPackageRepository();

            localRepository.AddPackage(packageA_10);

            var projectManager1 = new Mock <IProjectManager>();

            projectManager1.Setup(p => p.LocalRepository).Returns(localRepository);

            var project1 = MockProjectUtility.CreateMockProject("Project1");

            var packageManager = new Mock <IVsPackageManager>();

            packageManager.Setup(p => p.LocalRepository).Returns(localRepository);
            packageManager.Setup(p => p.SourceRepository).Returns(sourceRepository);
            packageManager.Setup(p => p.GetProjectManager(It.Is <Project>(s => s == project1))).Returns(projectManager1.Object);
            packageManager.Setup(p => p.IsProjectLevel(packageA_12)).Returns(false);

            var solutionManager = new Mock <ISolutionManager>();

            solutionManager.Setup(p => p.GetProject(It.Is <string>(s => s == "Project1"))).Returns(project1);
            solutionManager.Setup(p => p.GetProjects()).Returns(new Project[] { project1 });

            var mockWindowService = new Mock <IUserNotifierServices>();

            mockWindowService.Setup(p => p.ShowProjectSelectorWindow(
                                        It.IsAny <string>(),
                                        It.IsAny <IPackage>(),
                                        It.IsAny <Predicate <Project> >(),
                                        It.IsAny <Predicate <Project> >())).Returns(new Project[0]);

            var provider      = CreateSolutionUpdatesProvider(packageManager.Object, localRepository, solutionManager: solutionManager.Object, userNotifierServices: mockWindowService.Object);
            var extensionTree = provider.ExtensionsTree;

            var firstTreeNode = (SimpleTreeNode)extensionTree.Nodes[0];

            firstTreeNode.Repository.AddPackage(packageA_10);

            provider.SelectedNode = firstTreeNode;
            IVsPackageManager        activePackageManager = provider.GetActivePackageManager();
            Mock <IVsPackageManager> mockPackageManager   = Mock.Get <IVsPackageManager>(activePackageManager);

            var manualEvent = new ManualResetEventSlim(false);

            Exception exception = null;

            provider.ExecuteCompletedCallback = delegate
            {
                try
                {
                    // Assert
                    mockPackageManager.Verify(p => p.UpdatePackage(
                                                  new Project[0],
                                                  packageA_12,
                                                  new[] { new PackageOperation(packageA_10, PackageAction.Uninstall), new PackageOperation(packageA_12, PackageAction.Install) },
                                                  true,
                                                  false,
                                                  provider,
                                                  provider), Times.Once());
                }
                catch (Exception e)
                {
                    exception = e;
                }
                finally
                {
                    manualEvent.Set();
                }
            };

            var extensionA_12 = new PackageItem(provider, packageA_12);

            // Act
            provider.Execute(extensionA_12);

            // do not allow the method to return
            manualEvent.Wait();

            Assert.Null(exception);
        }
Example #43
0
        public void ConfiguredAwaiter_OnCompleted(bool continueOnCapturedContext)
        {
            // Since ValueTask implements both OnCompleted and UnsafeOnCompleted,
            // OnCompleted typically won't be used by await, so we add an explicit test
            // for it here.

            ValueTask<int> t = 42;
            var mres = new ManualResetEventSlim();
            t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => mres.Set());
            Assert.True(mres.Wait(10000));
        }
Example #44
0
        public void Awaiter_OnCompleted()
        {
            // Since ValueTask implements both OnCompleted and UnsafeOnCompleted,
            // OnCompleted typically won't be used by await, so we add an explicit test
            // for it here.

            ValueTask<int> t = new ValueTask<int>(42);
            var mres = new ManualResetEventSlim();
            t.GetAwaiter().OnCompleted(() => mres.Set());
            Assert.True(mres.Wait(10000));
        }