示例#1
0
        public void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment)
        {
            Assert.Equal(EnlistmentOutcome.Committed, _expectedOutcome);

            _outcomeReceived?.Set();

            singlePhaseEnlistment.Done();
        }
示例#2
0
 public void SetReset()
 {
     using (AutoResetEvent are = new AutoResetEvent(false))
     {
         Assert.False(are.WaitOne(0));
         are.Set();
         Assert.True(are.WaitOne(0));
         Assert.False(are.WaitOne(0));
         are.Set();
         are.Reset();
         Assert.False(are.WaitOne(0));
     }
 }
示例#3
0
    public bool PosTest1()
    {
        bool           retVal = true;
        AutoResetEvent are;

        TestLibrary.TestFramework.BeginScenario("PosTest1: AutoResetEvent.Set()");

        try
        {
            // false means that the initial state should be not signaled
            are = new AutoResetEvent(false);

            // set the signal
            if (!are.Set())
            {
                TestLibrary.TestFramework.LogError("001", "AutoResetEvent.Set() failed");
                retVal = false;
            }

            // verify that the autoreset event is signaled
            // if it is not signaled the following call will block for ever
            TestLibrary.TestFramework.LogInformation("Calling AutoResetEvent.WaitOne()... if the event is not signaled it will hang");
            are.WaitOne();

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
示例#4
0
 internal void Terminate()
 {
     terminate = true;
     try { callDispatcherRunEvent?.Set(); } catch (ObjectDisposedException) { }
     if (Dispatcher is not null && !Dispatcher.HasShutdownStarted && !Dispatcher.HasShutdownFinished)
     {
         Dispatcher.BeginInvokeShutdown();
     }
 }
示例#5
0
    private static void HandleCharacter(Match match, HttpListenerResponse response)
    {
        // here we are running in a thread different from the main thread
        int pid = Convert.ToInt32(match.Groups[1].Value);

        string responseString = "";

        // event used to wait the answer from the main thread.
        AutoResetEvent autoEvent = new AutoResetEvent(false);

        // var to store the character we are looking for
        Character character = null;
        // this bool is to check character is valid ... explanation below
        bool found = false;

        // we queue an 'action' to be executed in the main thread
        MainGameObject.QueueOnMainThread(()=>{
            // here we are in the main thread (see Update() in MainGameObject.cs)
            // retrieve the character
            character = MainGameObject.Instance().CharacterByID(pid);
            // if the character is null set found to false
            // have to do this because cannot call "character==null" elsewhere than the main thread
            // do not know why (yet?)
            // so if found this "trick"
            found = (character!=null?true:false);
            // set the event to "unlock" the thread
            autoEvent.Set();
        });

        // wait for the end of the 'action' executed in the main thread
        autoEvent.WaitOne();

        // generate the HTTP answer

        if (found==false) {
            responseString = "<html><body>character: not found (" + pid + ")</body></html>";
        } else {
            responseString = "<html><body>";
            responseString += "<img src='data:image/jpg;base64," + character.imageB64 + "'></img></br>";
            responseString += "name: " +  character.name + "</br>";
            responseString += "life: " +  character.life + "</br>";
            responseString += "streght " +  character.streght + "</br>";
            responseString += "dexterity " +  character.dexterity + "</br>";
            responseString += "consitution " +  character.consitution + "</br>";
            responseString += "intelligence " +  character.intelligence + "</br>";
            responseString += "</body></html>";
        }

        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        // Get a response stream and write the response to it.
        response.ContentLength64 = buffer.Length;
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer,0,buffer.Length);
        // You must close the output stream.
        output.Close();
    }
示例#6
0
    public void Go()
    {
        // find all the upcoming UK horse races (EventTypeId 7)
        var marketFilter = new MarketFilter();
        marketFilter.EventTypeIds = new HashSet<string>() { "7" };
        marketFilter.MarketStartTime = new TimeRange()
        {
            From = DateTime.Now,
            To = DateTime.Now.AddDays(2)
        };
        marketFilter.MarketTypeCodes = new HashSet<String>() { "WIN" };

        Console.WriteLine("BetfairClient.ListEvents()");
        var events = _client.ListEvents(marketFilter).Result;
        if (events.HasError)
            throw new ApplicationException();
        var firstEvent = events.Response.First();
        Console.WriteLine("First Event {0} {1}", firstEvent.Event.Id, firstEvent.Event.Name);

        var marketCatalogues = _client.ListMarketCatalogue(
          BFHelpers.HorseRaceFilter(),
          BFHelpers.HorseRaceProjection(),
          MarketSort.FIRST_TO_START,
          25).Result.Response;

        marketCatalogues.ForEach(c =>
        {
            _markets.Enqueue(c);
            Console.WriteLine(c.MarketName);
        });
        Console.WriteLine();

        while (_markets.Count > 0)
        {
            AutoResetEvent waitHandle = new AutoResetEvent(false);
            MarketCatalogue marketCatalogue;
            _markets.TryDequeue(out marketCatalogue);

            var marketSubscription = _streamingClient.SubscribeMarket(marketCatalogue.MarketId)
                .SubscribeOn(Scheduler.Default)
                .Subscribe(
                tick =>
                {
                    Console.WriteLine(BFHelpers.MarketSnapConsole(tick, marketCatalogue.Runners));
                },
                () =>
                {
                    Console.WriteLine("Market finished");
                    waitHandle.Set();
                });

            waitHandle.WaitOne();
            marketSubscription.Dispose();
        }
    }
示例#7
0
    public static AutoResetEvent WatchForEvents(FileSystemWatcher watcher, WatcherChangeTypes actions)
    {
        AutoResetEvent eventOccurred = new AutoResetEvent(false);

        if (0 != (actions & WatcherChangeTypes.Changed))
        {
            watcher.Changed += (o, e) =>
            {
                Assert.Equal(WatcherChangeTypes.Changed, e.ChangeType);
                eventOccurred.Set();
            };
        }

        if (0 != (actions & WatcherChangeTypes.Created))
        {
            watcher.Created += (o, e) =>
            {
                Assert.Equal(WatcherChangeTypes.Created, e.ChangeType);
                eventOccurred.Set();
            };
        }

        if (0 != (actions & WatcherChangeTypes.Deleted))
        {
            watcher.Deleted += (o, e) =>
            {
                Assert.Equal(WatcherChangeTypes.Deleted, e.ChangeType);
                eventOccurred.Set();
            };
        }

        if (0 != (actions & WatcherChangeTypes.Renamed))
        {
            watcher.Renamed += (o, e) =>
            {
                Assert.Equal(WatcherChangeTypes.Renamed, e.ChangeType);
                eventOccurred.Set();
            };
        }

        return eventOccurred;
    }
示例#8
0
 public void NonRepeatingTimer_ThatHasAlreadyFired_CanChangeAndFireAgain()
 {
     AutoResetEvent are = new AutoResetEvent(false);
     TimerCallback tc = new TimerCallback((object o) => are.Set());
     using (var t = new Timer(tc, null, 1, Timeout.Infinite))
     {
         Assert.True(are.WaitOne(MaxPositiveTimeoutInMs), "Should have received first timer event");
         Assert.False(are.WaitOne(500), "Should not have received a second timer event");
         t.Change(10, Timeout.Infinite);
         Assert.True(are.WaitOne(MaxPositiveTimeoutInMs), "Should have received a second timer event after changing it");
     }
 }
示例#9
0
    public void Timer_Fires_After_DueTime_Ellapses()
    {
        AutoResetEvent are = new AutoResetEvent(false);

        using (var t = new Timer(new TimerCallback((object s) =>
        {
            are.Set();
        }), null, TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
        {
            Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
        }
    }
示例#10
0
 public void Running_Timer_CanBeFinalizedAndStopsFiring()
 {
     AutoResetEvent are = new AutoResetEvent(false);
     TimerCallback tc = new TimerCallback((object o) => are.Set());
     var t = new Timer(tc, null, 1, 500);
     Assert.True(are.WaitOne(MaxPositiveTimeoutInMs), "Failed to get first timer fire");
     t = null; // Remove our refence so the timer can be GC'd
     GC.Collect();
     GC.WaitForPendingFinalizers();
     GC.Collect();
     Assert.False(are.WaitOne(500), "Should not have received a timer fire after it was collected");
 }
示例#11
0
        public void Prepare(PreparingEnlistment preparingEnlistment)
        {
            WasPreparedCalled = true;

            switch (_phase1Vote)
            {
            case Phase1Vote.Prepared:
            {
                if (_volatileEnlistDuringPrepare)
                {
                    TestEnlistment newVol = new TestEnlistment(_phase1Vote, _expectedOutcome);
                    try
                    {
                        _txToEnlist.EnlistVolatile(newVol, EnlistmentOptions.None);
                        Assert.True(_expectEnlistToSucceed);
                    }
                    catch (Exception)
                    {
                        Assert.False(_expectEnlistToSucceed);
                    }
                }
                preparingEnlistment.Prepared();
                break;
            }

            case Phase1Vote.ForceRollback:
            {
                _outcomeReceived?.Set();
                preparingEnlistment.ForceRollback();
                break;
            }

            case Phase1Vote.Done:
            {
                _outcomeReceived?.Set();
                preparingEnlistment.Done();
                break;
            }
            }
        }
示例#12
0
    public void Timer_Fires_AndPassesNullStateThroughCallback()
    {
        AutoResetEvent are = new AutoResetEvent(false);

        using (var t = new Timer(new TimerCallback((object s) =>
        {
            Assert.Null(s);
            are.Set();
        }), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
        {
            Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
        }
    }
示例#13
0
    public void Timer_Change_BeforeDueTime_ChangesWhenTimerWillFire()
    {
        AutoResetEvent are = new AutoResetEvent(false);

        using (var t = new Timer(new TimerCallback((object s) =>
        {
            are.Set();
        }), null, TimeSpan.FromSeconds(500), TimeSpan.FromMilliseconds(50)))
        {
            Assert.False(are.WaitOne(TimeSpan.FromMilliseconds(100)), "The reset event should not have been set yet");
            t.Change(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(-1));
            Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(TimerFiringTests.MaxPositiveTimeoutInMs)), "Should have received a timer event after this new duration");
        }
    }
示例#14
0
	public int Run()
	{
		Stopwatch sw = new Stopwatch();		
		AutoResetEvent are = new AutoResetEvent(false);
		sw.Start();
		bool ret = are.WaitOne(1000);//,false);
		sw.Stop();
		//We should never get signaled
		if(ret)
		{
			Console.WriteLine("AutoResetEvent should never be signalled.");
			return -1;
		}

		if(sw.ElapsedMilliseconds < 900)
		{
			Console.WriteLine("It should take at least 900 milliseconds to call bool ret = are.WaitOne(1000,false);.");
			Console.WriteLine("sw.ElapsedMilliseconds = " + sw.ElapsedMilliseconds);			
			return -2;
		}
		
		are.Set();
		if(!are.WaitOne(0))//,false))
		{
			Console.WriteLine("Signalled event should always return true on call to !are.WaitOne(0,false).");
			return -3;
		}
		
		sw.Reset();		
		sw.Start();
		ret = are.WaitOne(1000);//,false);
		sw.Stop();
		//We should never get signaled
		if(ret)
		{
			Console.WriteLine("AutoResetEvent should never be signalled after is is AutoReset.");
			return -4;
		}

		if(sw.ElapsedMilliseconds < 900)
		{
			Console.WriteLine("It should take at least 900 milliseconds to call bool ret = are.WaitOne(1000,false);.");
			Console.WriteLine("sw.ElapsedMilliseconds = " + sw.ElapsedMilliseconds);			
			return -5;
		}
		
		return 100;
		
	}
示例#15
0
    public void Timer_Fires_After_DueTime_AndOn_Period()
    {
        int count = 0;
        AutoResetEvent are = new AutoResetEvent(false);

        using (var t = new Timer(new TimerCallback((object s) =>
        {
            if (Interlocked.Increment(ref count) >= 2)
            {
                are.Set();
            }
        }), null, TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(50)))
        {
            Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
        }
    }
示例#16
0
    public void Timer_FiresOnlyOnce_OnDueTime_With_InfinitePeriod()
    {
        int count = 0;
        AutoResetEvent are = new AutoResetEvent(false);

        using (var t = new Timer(new TimerCallback((object s) =>
        {
            if (Interlocked.Increment(ref count) >= 2)
            {
                are.Set();
            }
        }), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
        {
            Assert.False(are.WaitOne(TimeSpan.FromMilliseconds(250 /*enough for 2 fires + buffer*/)));
        }
    }
示例#17
0
    public void Timer_Fires_After_DueTime_AndOn_Period()
    {
        int count = 0;
        AutoResetEvent are = new AutoResetEvent(false);

        using (var t = new Timer(new TimerCallback((object s) =>
        {
            count++;
            if (count >= 2)
            {
                are.Set();
            }
        }), null, TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(50)))
        {
            Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(2000)));
        }
    }
示例#18
0
    public void Timer_FiresOnlyOnce_OnDueTime_With_InfinitePeriod()
    {
        int count = 0;
        AutoResetEvent are = new AutoResetEvent(false);

        using (var t = new Timer(new TimerCallback((object s) =>
        {
            count++;
            if (count >= 2)
            {
                are.Set();
            }
        }), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
        {
            Assert.False(are.WaitOne(TimeSpan.FromSeconds(1)));
        }
    }
    public static void FileSystemWatcher_InternalBufferSize_File()
    {
        using (var file = Utility.CreateTestFile())
        using (var watcher = new FileSystemWatcher("."))
        {
            watcher.Filter = Path.GetFileName(file.Path);
            ManualResetEvent unblockHandler = new ManualResetEvent(false);
            watcher.Changed += (o, e) =>
            {
                // block the handling thread
                unblockHandler.WaitOne();
            };

            AutoResetEvent eventOccured = new AutoResetEvent(false);
            watcher.Error += (o, e) =>
            {
                eventOccured.Set();
            };
            watcher.EnableRaisingEvents = true;

            // See note in FileSystemWatcher_Error_File
            int originalInternalBufferOperationCapacity = watcher.InternalBufferSize / (16 + 2 * (file.Path.Length + 1));
            for (int i = 1; i < originalInternalBufferOperationCapacity * 2; i++)
            {
                File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(i));
            }

            unblockHandler.Set();
            Utility.ExpectEvent(eventOccured, "error");

            // Update InternalBufferSize to accomadate the data
            watcher.InternalBufferSize = watcher.InternalBufferSize * 2;
            unblockHandler.Reset();

            // Send the same number of events.
            for (int i = 1; i < originalInternalBufferOperationCapacity * 2; i++)
            {
                File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(i));
            }
            unblockHandler.Set();
            // This time we should not see an error
            Utility.ExpectNoEvent(eventOccured, "error");
        }
    }
示例#20
0
    protected override void Run()
    {
        MessageBox.Show("CustomSilentBA just starting...");
        try
        {
            var done = new AutoResetEvent(false);

            DetectPackageComplete += (s, e) =>
            {
                //Debug.Assert(false);

                //Presence or absence of MyProductPackageId product will be a deciding factor
                //for initializing BA for Install or Uninstall.
                if (e.PackageId == "MyProductPackageId")
                {
                    if (e.State == PackageState.Absent)
                        this.Engine.Plan(LaunchAction.Install);
                    else if (e.State == PackageState.Present)
                        this.Engine.Plan(LaunchAction.Uninstall);
                }
            };

            PlanComplete += (s, e) =>
            {
                if (e.Status >= 0)
                    this.Engine.Apply(IntPtr.Zero);
            };

            ApplyComplete += (s, e) =>
            {
                done.Set();
            };

            Engine.Detect();

            done.WaitOne();
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }
        Engine.Quit(0);
    }
示例#21
0
    public static int Main(String[] args)
    {
        var psi = new ProcessStartInfo();
        psi.FileName = "cmd.exe";
        //    psi.Arguments = String.Join(" ", args);
        psi.Arguments = "/C cmd.exe /K 2>&1";
        psi.WorkingDirectory = Directory.GetCurrentDirectory();
        psi.UseShellExecute = false;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        // NB: when you don't redirect standard error, it gets merged into standard output
        //    psi.RedirectStandardError = true;

        var p = new Process();
        p.StartInfo = psi;
        p.Exited += (o, e) => Environment.Exit(p.ExitCode);

        if (p.Start()) {
          var stdout = new StandardOutputReader(p);
        //      var stderr = new StandardErrorReader(p);

          while (!p.HasExited) {
        WaitHandle.WaitAll(new []{stdout.Blocked});
        //        WaitHandle.WaitAll(new []{stdout.Blocked, stderr.Blocked});

        var flag = new AutoResetEvent(false);
        var waiter = new Thread(() => { WaitHandle.WaitAny(new []{stdout.Unblocked}); flag.Set(); });
        //        var waiter = new Thread(() => { WaitHandle.WaitAny(new []{stdout.Unblocked, stderr.Unblocked}); flag.Set(); });
        var writer = new Thread(() => {
          var command = Console.ReadLine();
          HandleCommand(p, command);
        });

        waiter.Start();
        writer.Start();
        flag.WaitOne();
          }

          return p.ExitCode;
        } else {
          return -1;
        }
    }
示例#22
0
        /// <inheritdoc/>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    Clear();
                    _disposeTokenSource.Cancel();
                    _delaySignal?.Set();
                    (_cache as IDisposable)?.Dispose();
                    _disposeTokenSource.Dispose();
                    _delaySignal?.Dispose();
                }

                _delaySignal = null;

                _disposed = true;
            }
        }
示例#23
0
        private void StartReceiving()
        {
            while (_messageEventQueue.TryDequeue(out _))
            {
                // do nothing
            }

            _exitReceiving = new AutoResetEvent(false);
            _receivePong   = new AutoResetEvent(false);

            var frameStream = new WebSocketFrameStream(_stream);

            Task.Run(async() =>
            {
                while (_readyState == WebSocketState.Open)
                {
                    try
                    {
                        var frame = await frameStream.ReadFrameAsync(this).ConfigureAwait(false);

                        if (frame == null)
                        {
                            return;
                        }

                        var result = await ProcessReceivedFrame(frame).ConfigureAwait(false);

                        if (!result || _readyState == WebSocketState.Closed)
                        {
                            _exitReceiving?.Set();

                            return;
                        }

                        _ = Task.Run(Message);
                    }
                    catch (Exception ex)
                    {
                        Fatal("An exception has occurred while receiving.", ex);
                    }
                }
            });
        }
	public void TestWaitOneSingleThreaded()
	{
		bool x;

		e1 = new AutoResetEvent(false);

		x = e1.WaitOne(10,false);

		AssertEquals("WaitOne(unset)", x, false);

		e1.Set();

		x = e1.WaitOne(10,false);

		AssertEquals("WaitOne(set)", x, true);

		// It should be reset now.

		x = e1.WaitOne(10,false);

		AssertEquals("WaitOne(set)", x, false);
	}
    public static void CheckForMensagensAsync(Action<List<Mensagem>> onMensagens)
    {
        var queued = ThreadPool.QueueUserWorkItem(
            new WaitCallback(parm =>
                        {
                            var msgs = new List<Mensagem>();
                            var wait = new AutoResetEvent(false);
                            using (var subscriber = _mensagens.Subscribe(msg =>
                                                                            {
                                                                                msgs.Add(msg);
                                                                                wait.Set();
                                                                            }))
                            {
                                // espera maxima para uma nova mensagem
                                wait.WaitOne(TimeSpan.FromSeconds(MaxTimetoutSegundos));
                            }

                            ((Action<List<Mensagem>>)parm)(msgs);
                        }), onMensagens
        );

        if (!queued)
            onMensagens(new List<Mensagem>());
    }
 public void PingPong()
 {
     using (AutoResetEvent are1 = new AutoResetEvent(true), are2 = new AutoResetEvent(false))
     {
         const int Iters = 10;
         Task.WaitAll(
             Task.Factory.StartNew(() =>
             {
                 for (int i = 0; i < Iters; i++)
                 {
                     Assert.True(are1.WaitOne(FailedWaitTimeout));
                     are2.Set();
                 }
             }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default),
             Task.Factory.StartNew(() =>
             {
                 for (int i = 0; i < Iters; i++)
                 {
                     Assert.True(are2.WaitOne(FailedWaitTimeout));
                     are1.Set();
                 }
             }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default));
     }
 }
示例#27
0
        public StandardStreamReader(Process p, StreamReader stream)
        {
            this.Stream = stream;
              var lk = new Object();
              EventWaitHandle finishedReading = new AutoResetEvent(false);
              var reads = 0;

              var reader = new Thread(() => {
            try {
              while (!p.HasExited) {
            const int cnt = 1;
            var buf = new char[cnt];
            var n = TryRead(buf, 0, cnt);
            finishedReading.Set();
            if (n == 0) break;
            lock (lk) { reads++; }
            AfterChunkRead(new String(buf, 0, n));
              }
            } catch {
              var old = finishedReading;
              finishedReading = new ManualResetEvent(true);
              old.Set();
            }
              });

              var poller = new Thread(() => {
            while (!p.HasExited) {
              var success = finishedReading.WaitOne(50);
              if (!success) {
            Blocked.Set();
            Unblocked.Reset();
            finishedReading.WaitOne();
            Unblocked.Set();
            Blocked.Reset();
              }
            }
              });

              reader.Start();
              poller.Start();
        }
        private void ProcEvents()
        {
            bool   bDone = false;
            int    hr;
            bool   sp;
            int    i  = 0;
            IntPtr ip = IntPtr.Zero;

            while (!bDone)
            {
                while (m_Q.Count == 0)
                {
                    Thread.Sleep(1);
                }

                EventParams ep = (EventParams)m_Q.Dequeue();

                switch (ep.ec)
                {
                case EventCmd.Init:
                    Config2();
                    break;

                case EventCmd.Run:
                    m_mc.Run();
                    break;

                case EventCmd.Event:

                    Debug.WriteLine(ep.EventID);

                    if (ep.EventID == SBEEvent.StreamDescEvent)
                    {
                        if (!m_bWorked)
                        {
                            DVRStreamDesc sd = new DVRStreamDesc();

                            ip = IntPtr.Zero;
                            sp = false;
                            i  = 0;

                            hr = m_ge.GetEvent(ep.EventID, ep.Param1, ep.Param2, ep.Param3, ep.Param4, out sp, ref i, ip);
                            Thread.Sleep(1);
                            ip = Marshal.AllocCoTaskMem(i);
                            try
                            {
                                sp = false;
                                hr = m_ge.GetEvent(ep.EventID, ep.Param1, ep.Param2, ep.Param3, ep.Param4, out sp, ref i, ip);
                                Marshal.PtrToStructure(ip, sd);

                                m_bWorked = hr == 0 && sd.guidFormatType == sd.MediaType.formatType && sd.guidFormatType != Guid.Empty;
                            }
                            finally
                            {
                                Marshal.FreeCoTaskMem(ip);
                            }
                        }

                        break;
                    }
                    break;

                case EventCmd.Exit:
                    bDone = true;
                    break;
                }
                m_re.Set();
            }
        }
示例#29
0
 private void ProcessPongFrame()
 {
     _receivePong?.Set();
     "Received a pong.".Trace(nameof(ProcessPongFrame));
 }
示例#30
0
	public static int Main (string[] args)
	{ 
		Console.WriteLine ("Touch.Unit Simple Server");
		Console.WriteLine ("Copyright 2011, Xamarin Inc. All rights reserved.");
		
		bool help = false;
		bool verbose = false;
		string address = null;
		string port = null;
		string log_path = ".";
		string log_file = null;
		string launchdev = null;
		string launchsim = null;
		bool autoexit = false;
		string device_name = String.Empty;
		string device_type = String.Empty;
		TimeSpan? timeout = null;
		TimeSpan? startup_timeout = null;
		var mtouch_arguments = new List<string> ();

		var os = new OptionSet () {
			{ "h|?|help", "Display help", v => help = true },
			{ "verbose", "Display verbose output", v => verbose = true },
			{ "ip", "IP address to listen (default: Any)", v => address = v },
			{ "port", "TCP port to listen (default: Any)", v => port = v },
			{ "logpath", "Path to save the log files (default: .)", v => log_path = v },
			{ "logfile=", "Filename to save the log to (default: automatically generated)", v => log_file = v },
			{ "launchdev=", "Run the specified app on a device (specify using bundle identifier)", v => launchdev = v },
			{ "launchsim=", "Run the specified app on the simulator (specify using path to *.app directory)", v => launchsim = v },
			{ "autoexit", "Exit the server once a test run has completed (default: false)", v => autoexit = true },
			{ "devname=", "Specify the device to connect to", v => device_name = v},
			{ "device=", "Specifies the device type to launch the simulator", v => device_type = v },
			{ "timeout=", "Specifies a timeout (in minutes), after which the simulator app will be killed (ignored for device runs)", v => timeout = TimeSpan.FromMinutes (double.Parse (v)) },
			{ "startup-timeout=", "Specifies a timeout (in seconds) for the simulator app to connect to Touch.Server (ignored for device runs)", v => startup_timeout = TimeSpan.FromSeconds (double.Parse (v)) },
			{ "mtouch-argument=", "Specifies an extra mtouch argument when launching the application", v => mtouch_arguments.Add (v) },
		};
		
		try {
			os.Parse (args);
			if (help)
				ShowHelp (os);
			
			var listener = new SimpleListener ();
			
			IPAddress ip;
			if (String.IsNullOrEmpty (address) || !IPAddress.TryParse (address, out ip))
				listener.Address = IPAddress.Any;
			
			ushort p;
			if (UInt16.TryParse (port, out p))
				listener.Port = p;
			
			listener.LogPath = log_path ?? ".";
			listener.LogFile = log_file;
			listener.AutoExit = autoexit;
			listener.Initialize ();
			
			string mt_root = Environment.GetEnvironmentVariable ("MONOTOUCH_ROOT");
			if (String.IsNullOrEmpty (mt_root))
				mt_root = "/Developer/MonoTouch";

			string mtouch = Path.Combine (mt_root, "bin", "mtouch");
			if (!File.Exists (mtouch))
				mtouch = Path.Combine (mt_root, "usr", "bin", "mtouch");

			Process proc = null;
			if (launchdev != null) {
				ThreadPool.QueueUserWorkItem ((v) => {
					{
						proc = new Process ();
						StringBuilder output = new StringBuilder ();
						StringBuilder procArgs = new StringBuilder ();
						string sdk_root = Environment.GetEnvironmentVariable ("XCODE_DEVELOPER_ROOT");
						if (!String.IsNullOrEmpty (sdk_root))
							procArgs.Append ("--sdkroot ").Append (sdk_root);
						procArgs.Append (" --launchdev ");
						procArgs.Append (Quote (launchdev));
						if (!String.IsNullOrEmpty (device_name))
							procArgs.Append (" --devname=").Append (Quote (device_name));
						procArgs.Append (" -argument=-connection-mode -argument=none");
						procArgs.Append (" -argument=-app-arg:-autostart");
						procArgs.Append (" -argument=-app-arg:-autoexit");
						procArgs.Append (" -argument=-app-arg:-enablenetwork");
						procArgs.AppendFormat (" -argument=-app-arg:-hostport:{0}", listener.Port);
						procArgs.Append (" -argument=-app-arg:-hostname:");
						foreach (var arg in mtouch_arguments)
							procArgs.Append (" ").Append (arg);
						var ipAddresses = System.Net.Dns.GetHostEntry (System.Net.Dns.GetHostName ()).AddressList;
						for (int i = 0; i < ipAddresses.Length; i++) {
							if (i > 0)
								procArgs.Append (',');
							procArgs.Append (ipAddresses [i].ToString ());
						}
						proc.StartInfo.FileName = mtouch;
						proc.StartInfo.Arguments = procArgs.ToString ();
						proc.StartInfo.UseShellExecute = false;
						proc.StartInfo.RedirectStandardOutput = true;
						proc.StartInfo.RedirectStandardError = true;
						proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							lock (output) {
								output.Append ("[mtouch stderr] ");
								output.AppendLine (e.Data);
							}
						};
						proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							lock (output) {
								output.Append ("[mtouch stdout] ");
								output.AppendLine (e.Data);
							}
						};
						proc.Start ();
						proc.BeginErrorReadLine ();
						proc.BeginOutputReadLine ();
						proc.WaitForExit ();
						if (proc.ExitCode != 0)
							listener.Cancel ();
						Console.WriteLine (output.ToString ());
					}
				});
			}

			var lastErrorDataReceived = new AutoResetEvent (true);
			var lastOutDataReceived = new AutoResetEvent (true);
			if (launchsim != null) {
				lastErrorDataReceived.Reset ();
				lastOutDataReceived.Reset ();

				ThreadPool.QueueUserWorkItem ((v) => {
					{
						proc = new Process ();
						int pid = 0;
						StringBuilder output = new StringBuilder ();
						StringBuilder procArgs = new StringBuilder ();
						string sdk_root = Environment.GetEnvironmentVariable ("XCODE_DEVELOPER_ROOT");
						if (!String.IsNullOrEmpty (sdk_root))
							procArgs.Append ("--sdkroot ").Append (sdk_root);
						procArgs.Append (" --launchsim ");
						procArgs.Append (Quote (launchsim));
						if (!string.IsNullOrEmpty (device_type))
							procArgs.Append (" --device ").Append (device_type);
						procArgs.Append (" -argument=-connection-mode -argument=none");
						procArgs.Append (" -argument=-app-arg:-autostart");
						procArgs.Append (" -argument=-app-arg:-autoexit");
						procArgs.Append (" -argument=-app-arg:-enablenetwork");
						procArgs.Append (" -argument=-app-arg:-hostname:127.0.0.1");
						procArgs.AppendFormat (" -argument=-app-arg:-hostport:{0}", listener.Port);
						foreach (var arg in mtouch_arguments)
							procArgs.Append (" ").Append (arg);
						proc.StartInfo.FileName = mtouch;
						proc.StartInfo.Arguments = procArgs.ToString ();
						proc.StartInfo.UseShellExecute = false;
						proc.StartInfo.RedirectStandardError = true;
						proc.StartInfo.RedirectStandardOutput = true;
						proc.StartInfo.RedirectStandardInput = true;

						proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							if (e.Data == null) {
								Console.WriteLine ("[mtouch stderr EOS]");
								lastErrorDataReceived.Set ();
								return;
							}
							Console.WriteLine ("[mtouch stderr {0}] {1}", DateTime.Now.ToLongTimeString (), e.Data);
						};
						proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							if (e.Data == null){
								Console.WriteLine ("[mtouch stdout EOS]");
								lastOutDataReceived.Set ();
								return;
							}
							Console.WriteLine ("[mtouch stdout {0}] {1}", DateTime.Now.ToLongTimeString (), e.Data);

							if (e.Data.StartsWith ("Application launched. PID = ")) {
								var pidstr = e.Data.Substring ("Application launched. PID = ".Length);
								if (!int.TryParse (pidstr, out pid)) {
									Console.WriteLine ("Could not parse pid: {0}", pidstr);
								} else if (startup_timeout.HasValue) {
									ThreadPool.QueueUserWorkItem ((v2) =>
										{
											if (!listener.WaitForConnection (startup_timeout.Value))
												KillPid (proc, pid, 1000, startup_timeout.Value, "Startup");
										});
								}
							}
						};
						if (verbose)
							Console.WriteLine ("{0} {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments);
						proc.Start ();
						proc.BeginErrorReadLine ();
						proc.BeginOutputReadLine ();
						if (timeout.HasValue) {
							if (!proc.WaitForExit ((int) timeout.Value.TotalMilliseconds)) {
								if (pid != 0) {
									KillPid (proc, pid, 5000, timeout.Value, "Completion");
								} else {
									proc.StandardInput.WriteLine (); // this kills as well, but we won't be able to send SIGQUIT to get a stack trace.
								}
								if (!proc.WaitForExit (5000 /* wait another 5 seconds for mtouch to finish as well */))
									Console.WriteLine ("mtouch didn't complete within 5s of killing the simulator app. Touch.Server will exit anyway.");
							}
						} else {
							proc.WaitForExit ();
						}
						listener.Cancel ();
					}
				});
			}
			
			var result = listener.Start ();
			if (proc != null && !proc.WaitForExit (10000 /* wait another 10 seconds for mtouch to finish as well */))
				Console.WriteLine ("mtouch didn't complete within 10s of the simulator app exiting. Touch.Server will exit anyway.");
			// Wait up to 2 seconds to receive the last of the error/output data. This will only be received *after*
			// mtouch has exited.
			lastErrorDataReceived.WaitOne (2000);
			lastOutDataReceived.WaitOne (2000);
			return result;
		} catch (OptionException oe) {
			Console.WriteLine ("{0} for options '{1}'", oe.Message, oe.OptionName);
			return 1;
		} catch (Exception ex) {
			Console.WriteLine (ex);
			return 1;
		}
	}   
        public static void WaitNotificationTest()
        {
            ThreadTestHelpers.RunTestInBackgroundThread(() =>
            {
                var tsc = new TestSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(tsc);
                Assert.Same(tsc, SynchronizationContext.Current);

                var e = new ManualResetEvent(false);
                tsc.WaitAction = () => e.Set();
                Assert.False(tsc.IsWaitNotificationRequired());
                Assert.False(e.WaitOne(0));
                tsc.SetWaitNotificationRequired();
                Assert.True(tsc.IsWaitNotificationRequired());
                Assert.True(e.WaitOne(0));

                var mres = new ManualResetEventSlim();
                tsc.WaitAction = () => mres.Set();
                mres.Reset();
                mres.CheckedWait();

                e.Reset();
                tsc.WaitAction = () => e.Set();
                SynchronizationContext.SetSynchronizationContext(new TestSynchronizationContext());
                Assert.False(e.WaitOne(0));
                SynchronizationContext.SetSynchronizationContext(tsc);
                Assert.True(e.WaitOne(0));
                e.Reset();
                e.CheckedWait();

                e.Reset();
                var lockObj = new object();
                var lockAcquiredFromBackground = new AutoResetEvent(false);
                Action waitForThread;
                Thread t =
                    ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
                    {
                        lock (lockObj)
                        {
                            lockAcquiredFromBackground.Set();
                            e.CheckedWait();
                        }
                    });
                t.IsBackground = true;
                t.Start();
                lockAcquiredFromBackground.CheckedWait();
                Assert.True(Monitor.TryEnter(lockObj, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
                Monitor.Exit(lockObj);
                waitForThread();

                e.Reset();
                var m = new Mutex();
                t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
                {
                    m.CheckedWait();
                    try
                    {
                        lockAcquiredFromBackground.Set();
                        e.CheckedWait();
                    }
                    finally
                    {
                        m.ReleaseMutex();
                    }
                });
                t.IsBackground = true;
                t.Start();
                lockAcquiredFromBackground.CheckedWait();
                m.CheckedWait();
                m.ReleaseMutex();
                waitForThread();
            });
        }
示例#32
0
        public static void QueueRegisterPositiveAndFlowTest()
        {
            var asyncLocal = new AsyncLocal<int>();
            asyncLocal.Value = 1;

            var obj = new object();
            var registerWaitEvent = new AutoResetEvent(false);
            var threadDone = new AutoResetEvent(false);
            RegisteredWaitHandle registeredWaitHandle = null;
            Exception backgroundEx = null;
            int backgroundAsyncLocalValue = 0;

            Action<bool, Action> commonBackgroundTest =
                (isRegisteredWaitCallback, test) =>
                {
                    try
                    {
                        if (isRegisteredWaitCallback)
                        {
                            RegisteredWaitHandle toUnregister = registeredWaitHandle;
                            registeredWaitHandle = null;
                            Assert.True(toUnregister.Unregister(threadDone));
                        }
                        test();
                        backgroundAsyncLocalValue = asyncLocal.Value;
                    }
                    catch (Exception ex)
                    {
                        backgroundEx = ex;
                    }
                    finally
                    {
                        if (!isRegisteredWaitCallback)
                        {
                            threadDone.Set();
                        }
                    }
                };
            Action<bool> waitForBackgroundWork =
                isWaitForRegisteredWaitCallback =>
                {
                    if (isWaitForRegisteredWaitCallback)
                    {
                        registerWaitEvent.Set();
                    }
                    threadDone.CheckedWait();
                    if (backgroundEx != null)
                    {
                        throw new AggregateException(backgroundEx);
                    }
                };

            ThreadPool.QueueUserWorkItem(
                state =>
                {
                    commonBackgroundTest(false, () =>
                    {
                        Assert.Same(obj, state);
                    });
                },
                obj);
            waitForBackgroundWork(false);
            Assert.Equal(1, backgroundAsyncLocalValue);

            ThreadPool.UnsafeQueueUserWorkItem(
                state =>
                {
                    commonBackgroundTest(false, () =>
                    {
                        Assert.Same(obj, state);
                    });
                },
                obj);
            waitForBackgroundWork(false);
            Assert.Equal(0, backgroundAsyncLocalValue);

            registeredWaitHandle =
                ThreadPool.RegisterWaitForSingleObject(
                    registerWaitEvent,
                    (state, timedOut) =>
                    {
                        commonBackgroundTest(true, () =>
                        {
                            Assert.Same(obj, state);
                            Assert.False(timedOut);
                        });
                    },
                    obj,
                    UnexpectedTimeoutMilliseconds,
                    false);
            waitForBackgroundWork(true);
            Assert.Equal(1, backgroundAsyncLocalValue);

            registeredWaitHandle =
                ThreadPool.UnsafeRegisterWaitForSingleObject(
                    registerWaitEvent,
                    (state, timedOut) =>
                    {
                        commonBackgroundTest(true, () =>
                        {
                            Assert.Same(obj, state);
                            Assert.False(timedOut);
                        });
                    },
                    obj,
                    UnexpectedTimeoutMilliseconds,
                    false);
            waitForBackgroundWork(true);
            Assert.Equal(0, backgroundAsyncLocalValue);
        }
示例#33
0
        public static IEnumerable <T> LookAhead <T>(Func <IEnumerable <T> > values, CancellationToken cancelToken)
        {
            // setup task completion sources to read results of look ahead
            using (var resultWriteEvent = new AutoResetEvent(false))
                using (var resultReadEvent = new AutoResetEvent(false))
                    using (var internalCancelToken = new CancellationTokenSource())
                    {
                        var results         = new ConcurrentQueue <T>();
                        var resultReadIndex = new[] { -1 };
                        var targetIndex     = new[] { 0 };

                        var resultsCount = 0;
                        var finalCount   = -1;

                        var readTimes = new List <DateTime>();
                        readTimes.Add(DateTime.UtcNow);

                        var exceptions = new ConcurrentBag <Exception>();

                        var lookAheadThread = new Thread(() =>
                        {
                            try
                            {
                                // look-ahead loop
                                var indexLocal  = 0;
                                var valuesLocal = values();
                                foreach (var value in valuesLocal)
                                {
                                    // cooperative loop
                                    if (internalCancelToken.IsCancellationRequested || (cancelToken != null && cancelToken.IsCancellationRequested))
                                    {
                                        return;
                                    }

                                    // store the result and notify
                                    results.Enqueue(value);
                                    resultsCount++;
                                    resultWriteEvent.Set();

                                    // make sure look-ahead doesn't go too far ahead, based on calculated index above
                                    while (indexLocal > targetIndex[0])
                                    {
                                        // cooperative loop
                                        if (internalCancelToken.IsCancellationRequested || (cancelToken != null && cancelToken.IsCancellationRequested))
                                        {
                                            return;
                                        }

                                        // wait for a result to be read
                                        resultReadEvent.WaitOne(TimeSpan.FromMilliseconds(10));
                                    }

                                    indexLocal++;
                                }

                                // notify done
                                finalCount = resultsCount;
                                resultWriteEvent.Set();
                            }
                            catch (Exception e)
                            {
                                // notify the enumerator loop of any exceptions
                                exceptions.Add(e);
                                resultWriteEvent.Set();
                            }
                        });
                        lookAheadThread.Name = "LookAhead.{0}".Format2(typeof(T));

                        lookAheadThread.Start();
                        try
                        {
                            // enumerate the results
                            var i = 0;
                            while (finalCount == -1 || i < finalCount)
                            {
                                // cooperative loop
                                if (cancelToken != null)
                                {
                                    cancelToken.ThrowIfCancellationRequested();
                                }

                                // unblock loook-ahead and wait for current result to be come available
                                resultReadEvent.Set();
                                while (i >= resultsCount && (finalCount == -1 || i < finalCount) && exceptions.Count == 0)
                                {
                                    // cooperative loop
                                    if (cancelToken != null)
                                    {
                                        cancelToken.ThrowIfCancellationRequested();
                                    }

                                    resultWriteEvent.WaitOne(TimeSpan.FromMilliseconds(10));
                                }

                                // check if any exceptions occurred in the look-ahead loop
                                if (exceptions.Count > 0)
                                {
                                    throw new AggregateException(exceptions);
                                }

                                // check if enumration is finished
                                if (finalCount != -1 && i >= finalCount)
                                {
                                    break;
                                }

                                // retrieve current result and clear reference
                                T result;
                                if (!results.TryDequeue(out result))
                                {
                                    throw new Exception();
                                }

                                // update current index and unblock look-ahead
                                resultReadIndex[0] = i;
                                resultReadEvent.Set();
                                i++;

                                // store time the result was read
                                readTimes.Add(DateTime.UtcNow);
                                while (readTimes.Count > 500)
                                {
                                    readTimes.RemoveAt(0);
                                }

                                // calculate how far to look-ahead based on how quickly the results are being read
                                var firstReadTime      = readTimes[0];
                                var readPerMillisecond = (float)(readTimes.Count / (DateTime.UtcNow - firstReadTime).TotalMilliseconds);
                                if (float.IsNaN(readPerMillisecond))
                                {
                                    readPerMillisecond = 0;
                                }
                                targetIndex[0] = resultReadIndex[0] + 1 + (int)(readPerMillisecond * 1000); // look ahead 1000 milliseconds

                                // yield result
                                yield return(result);
                            }
                        }
                        finally
                        {
                            // ensure look-ahead thread is cleaned up
                            internalCancelToken.Cancel();
                            lookAheadThread.Join();
                        }
                    }
        }
示例#34
0
 private static void OnExit(object sender, ConsoleCancelEventArgs args)
 {
     Closing.Set();
 }
示例#35
0
 private void btnAbort_Click(object sender, EventArgs e)
 {
     btnAbort.Enabled = false;
     m_evtCancel.Set();
     m_evtGlobalCancel.Set();
 }
 public void Exit()
 {
     notEntered.Set();
 }
示例#37
0
 public virtual void Cleanup()
 {
     _areStartStop.Set();
 }
示例#38
0
        public async Task EventDispatcher_EventsCoalesced2()
        {
            var waitDispatched = new AutoResetEvent(false);
            var executor       = new MockJavaScriptExecutor
            {
                OnCallFunctionReturnFlushedQueue = (p0, p1, p2) =>
                {
                    waitDispatched.Set();
                    return(EmptyResponse);
                },
                OnFlushQueue = () => EmptyResponse,
                OnInvokeCallbackAndReturnFlushedQueue = (_, __) => EmptyResponse
            };

            var context = await CreateContextAsync(executor);

            var dispatcher = new EventDispatcher(context);
            await DispatcherHelpers.RunOnDispatcherAsync(dispatcher.OnResume);

            var winner   = default(int);
            var disposed = new AutoResetEvent(false);

            var firstEvent  = new TestEvent(42, TimeSpan.MaxValue, "foo", 1, () => winner = 1, () => disposed.Set());
            var secondEvent = new TestEvent(42, TimeSpan.Zero, "foo", 1, () => winner = 2, () => disposed.Set());

            using (BlockJavaScriptThread(context))
            {
                dispatcher.DispatchEvent(firstEvent);
                dispatcher.DispatchEvent(secondEvent);

                // First event is disposed after coalesce
                Assert.IsTrue(disposed.WaitOne());
            }

            Assert.IsTrue(waitDispatched.WaitOne());
            Assert.AreEqual(1, winner);
            Assert.IsFalse(waitDispatched.WaitOne(500));

            // Second event is disposed after dispatch
            Assert.IsTrue(disposed.WaitOne());

            await DispatcherHelpers.RunOnDispatcherAsync(context.Dispose);
        }
示例#39
0
 private void synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
 {
     speakCompletedEvent.Set();
 }
        public void MustExecuteAsynchronously()
        {
            var configuration = new Mock <IFeatureConfiguration>();
            var sync          = new AutoResetEvent(false);
            var threadId      = Thread.CurrentThread.ManagedThreadId;

            configuration.Setup(c => c.GetStatus()).Callback(() => { threadId = Thread.CurrentThread.ManagedThreadId; sync.Set(); });

            sut.Observe(configuration.Object, FeatureConfigurationStatus.Disabled);
            sut.Start();
            sync.WaitOne();
            sut.Reset();

            Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, threadId);
        }
示例#41
0
 private void CloseButton_Click(object sender, EventArgs e)
 {
     _resetEvent.Set();
     ClearAndClose();
 }
示例#42
0
        private static SimpleJavaResponse Run_Java_Executable(string Arguments)
        {
            // Using string builders to collect the standard output and error
            StringBuilder output   = new StringBuilder();
            StringBuilder error    = new StringBuilder();
            int           exitCode = -1;


            // Perform all this work within using tag to encourage disposing of the process and events
            using (Process startSolrProcess = new Process())
                using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
                    using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                    {
                        startSolrProcess.StartInfo.FileName  = Java_Executable;
                        startSolrProcess.StartInfo.Arguments = Arguments;

                        startSolrProcess.StartInfo.UseShellExecute        = false;
                        startSolrProcess.StartInfo.RedirectStandardOutput = true;
                        startSolrProcess.StartInfo.RedirectStandardError  = true;
                        startSolrProcess.StartInfo.CreateNoWindow         = true;

                        // Add a function to handle asynchronous reading of the standard output
                        startSolrProcess.OutputDataReceived += (sender, e) =>
                        {
                            if (e.Data == null)
                            {
                                outputWaitHandle.Set();
                            }
                            else
                            {
                                output.AppendLine("     " + e.Data);
                            }
                        };

                        // Add a function to handle asynchronous reading of the standard error
                        startSolrProcess.ErrorDataReceived += (sender, e) =>
                        {
                            if (e.Data == null)
                            {
                                errorWaitHandle.Set();
                            }
                            else
                            {
                                error.AppendLine("     " + e.Data);
                            }
                        };

                        // Start the process
                        startSolrProcess.Start();

                        // Start the asyncronous reading of the standard input and standard output
                        startSolrProcess.BeginOutputReadLine();
                        startSolrProcess.BeginErrorReadLine();

                        // Wait for the process to copmlete
                        if (startSolrProcess.WaitForExit(2000))
                        {
                            // Give the output readers slightly more time to finish any reading
                            if (outputWaitHandle.WaitOne(100) && errorWaitHandle.WaitOne(100))
                            {
                                // Successfully ended and process completed.  Check process exit code here.
                                exitCode = startSolrProcess.ExitCode;
                            }
                        }
                        else
                        {
                            // Timed out.
                            startSolrProcess.Close();
                        }

                        // Ensure the output and error read events are not fired again
                        try
                        {
                            startSolrProcess.CancelOutputRead();
                        }
                        catch {  }

                        try
                        {
                            startSolrProcess.CancelErrorRead();
                        }
                        catch { }
                    }

            return(new SimpleJavaResponse(exitCode, (output + Environment.NewLine + error).Trim()));
        }
示例#43
0
 public void Dispose()
 {
     _disposeEvent.Set();
     _thread.Join();
 }
示例#44
0
        } // AddHookChannelUri

        //
        // end of IChannelReceiverHook implementation
        //


        //
        // Server helpers
        //

        // Thread for listening
        void Listen()
        {
            bool bOkToListen = false;

            try
            {
                _tcpListener.Start();
                bOkToListen = true;
            }
            catch (Exception e)
            {
                _startListeningException = e;
            }

            _waitForStartListening.Set(); // allow main thread to continue now that we have tried to start the socket

            InternalRemotingServices.RemotingTrace("Waiting to Accept the Socket on Port: " + _port);

            //
            // Wait for an incoming socket
            //
            Socket socket;

            while (bOkToListen)
            {
                InternalRemotingServices.RemotingTrace("TCPChannel::Listen - tcpListen.Pending() == true");

                try
                {
                    socket = _tcpListener.AcceptSocket();

                    if (socket == null)
                    {
                        throw new RemotingException(
                                  String.Format(
                                      CoreChannel.GetResourceString("Remoting_Socket_Accept"),
                                      Marshal.GetLastWin32Error().ToString()));
                    }
                    else
                    {
                        // disable nagle delay
                        socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);

                        // set linger option
                        LingerOption lingerOption = new LingerOption(true, 3);
                        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);

                        HttpServerSocketHandler streamManager = new HttpServerSocketHandler(socket, CoreChannel.RequestQueue);
                        streamManager.DataArrivedCallback = new WaitCallback(_transportSink.ServiceRequest);
                        streamManager.BeginReadMessage();
                    }
                }
                catch (Exception e)
                {
                    if (!_bListening)
                    {
                        // We called Stop() on the tcp listener, so gracefully exit.
                        bOkToListen = false;
                    }
                    else
                    {
                        // we want the exception to show up as unhandled since this
                        //   is an unexpected failure.
                        if (!(e is SocketException))
                        {
                            //throw;
                        }
                    }
                }
            } // while (bOkToListen)
        }
示例#45
0
   public static void Go() {
      // Construct an AutoResetEvent (initially false)
      AutoResetEvent are = new AutoResetEvent(false);

      // Tell the thread pool to wait on the AutoResetEvent
      RegisteredWaitHandle rwh = ThreadPool.RegisterWaitForSingleObject(
         are,             // Wait on this AutoResetEvent
         EventOperation,  // When available, call the EventOperation method
         null,            // Pass null to EventOperation
         5000,            // Wait 5 seconds for the event to become true
         false);          // Call EventOperation everytime the event is true

      // Start our loop
      Char operation = (Char)0;
      while (operation != 'Q') {
         Console.WriteLine("S=Signal, Q=Quit?");
         operation = Char.ToUpper(Console.ReadKey(true).KeyChar);
         if (operation == 'S') are.Set(); // User want to set the event
      }

      // Tell the thread pool to stop waiting on the event
      rwh.Unregister(null);
   }
示例#46
0
        /// <summary>
        /// Initialize the cache.
        /// </summary>
        internal void Initialize()
        {
            if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
            {
                _cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);

                bool isReadOnly = _cacheManager.IsReadOnly;

                HashSet <Hash128> invalidEntries = null;

                if (isReadOnly)
                {
                    Logger.Warning?.Print(LogClass.Gpu, "Loading shader cache in read-only mode (cache in use by another program!)");
                }
                else
                {
                    invalidEntries = new HashSet <Hash128>();
                }

                ReadOnlySpan <Hash128> guestProgramList = _cacheManager.GetGuestProgramList();

                _progressReportEvent.Reset();
                _shaderCount = 0;

                ShaderCacheStateChanged?.Invoke(true);
                ThreadPool.QueueUserWorkItem(ProgressLogger, guestProgramList.Length);

                for (int programIndex = 0; programIndex < guestProgramList.Length; programIndex++)
                {
                    Hash128 key = guestProgramList[programIndex];

                    byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
                    bool   hasHostCache      = hostProgramBinary != null;

                    IProgram hostProgram = null;

                    // If the program sources aren't in the cache, compile from saved guest program.
                    byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);

                    if (guestProgram == null)
                    {
                        Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");

                        // Should not happen, but if someone messed with the cache it's better to catch it.
                        invalidEntries?.Add(key);

                        continue;
                    }

                    ReadOnlySpan <byte> guestProgramReadOnlySpan = guestProgram;

                    ReadOnlySpan <GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);

                    if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
                    {
                        Debug.Assert(cachedShaderEntries.Length == 1);

                        GuestShaderCacheEntry entry = cachedShaderEntries[0];

                        HostShaderCacheEntry[] hostShaderEntries = null;

                        // Try loading host shader binary.
                        if (hasHostCache)
                        {
                            hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                            hostProgramBinary = hostProgramBinarySpan.ToArray();
                            hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                        }

                        bool isHostProgramValid = hostProgram != null;

                        ShaderProgram     program;
                        ShaderProgramInfo shaderProgramInfo;

                        // Reconstruct code holder.
                        if (isHostProgramValid)
                        {
                            program           = new ShaderProgram(entry.Header.Stage, "");
                            shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();
                        }
                        else
                        {
                            IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                            program = Translator.CreateContext(0, gpuAccessor, DefaultFlags | TranslationFlags.Compute).Translate(out shaderProgramInfo);
                        }

                        ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);

                        // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
                        if (hostProgram == null)
                        {
                            Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                            // Compile shader and create program as the shader program binary got invalidated.
                            shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
                            hostProgram       = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);

                            // As the host program was invalidated, save the new entry in the cache.
                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });

                            if (!isReadOnly)
                            {
                                if (hasHostCache)
                                {
                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                }
                                else
                                {
                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                }
                            }
                        }

                        _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
                    }
                    else
                    {
                        Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);

                        ShaderCodeHolder[]   shaders        = new ShaderCodeHolder[cachedShaderEntries.Length];
                        List <ShaderProgram> shaderPrograms = new List <ShaderProgram>();

                        TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformFeedbackInformation(ref guestProgramReadOnlySpan, fileHeader);

                        TranslationFlags flags = DefaultFlags;

                        if (tfd != null)
                        {
                            flags = TranslationFlags.Feedback;
                        }

                        TranslationCounts counts = new TranslationCounts();

                        HostShaderCacheEntry[] hostShaderEntries = null;

                        // Try loading host shader binary.
                        if (hasHostCache)
                        {
                            hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                            hostProgramBinary = hostProgramBinarySpan.ToArray();
                            hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                        }

                        bool isHostProgramValid = hostProgram != null;

                        // Reconstruct code holder.
                        for (int i = 0; i < cachedShaderEntries.Length; i++)
                        {
                            GuestShaderCacheEntry entry = cachedShaderEntries[i];

                            if (entry == null)
                            {
                                continue;
                            }

                            ShaderProgram program;

                            if (entry.Header.SizeA != 0)
                            {
                                ShaderProgramInfo shaderProgramInfo;

                                if (isHostProgramValid)
                                {
                                    program           = new ShaderProgram(entry.Header.Stage, "");
                                    shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                }
                                else
                                {
                                    IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                    TranslatorContext translatorContext  = Translator.CreateContext(0, gpuAccessor, flags, counts);
                                    TranslatorContext translatorContext2 = Translator.CreateContext((ulong)entry.Header.Size, gpuAccessor, flags | TranslationFlags.VertexA, counts);

                                    program = translatorContext.Translate(out shaderProgramInfo, translatorContext2);
                                }

                                // NOTE: Vertex B comes first in the shader cache.
                                byte[] code  = entry.Code.AsSpan().Slice(0, entry.Header.Size).ToArray();
                                byte[] code2 = entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray();

                                shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
                            }
                            else
                            {
                                ShaderProgramInfo shaderProgramInfo;

                                if (isHostProgramValid)
                                {
                                    program           = new ShaderProgram(entry.Header.Stage, "");
                                    shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                }
                                else
                                {
                                    IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                    program = Translator.CreateContext(0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
                                }

                                shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
                            }

                            shaderPrograms.Add(program);
                        }

                        // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
                        if (!isHostProgramValid)
                        {
                            Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                            List <IShader> hostShaders = new List <IShader>();

                            // Compile shaders and create program as the shader program binary got invalidated.
                            for (int stage = 0; stage < Constants.ShaderStages; stage++)
                            {
                                ShaderProgram program = shaders[stage]?.Program;

                                if (program == null)
                                {
                                    continue;
                                }

                                IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);

                                shaders[stage].HostShader = hostShader;

                                hostShaders.Add(hostShader);
                            }

                            hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);

                            // As the host program was invalidated, save the new entry in the cache.
                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);

                            if (!isReadOnly)
                            {
                                if (hasHostCache)
                                {
                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                }
                                else
                                {
                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                }
                            }
                        }

                        _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
                    }

                    _shaderCount = programIndex;
                }

                if (!isReadOnly)
                {
                    // Remove entries that are broken in the cache
                    _cacheManager.RemoveManifestEntries(invalidEntries);
                    _cacheManager.FlushToArchive();
                    _cacheManager.Synchronize();
                }

                _progressReportEvent.Set();
                ShaderCacheStateChanged?.Invoke(false);

                Logger.Info?.Print(LogClass.Gpu, $"Shader cache loaded {_shaderCount} entries.");
            }
        }
    public static void FileSystemWatcher_Error_File()
    {
        using (var file = Utility.CreateTestFile())
        using (var watcher = new FileSystemWatcher("."))
        {
            watcher.Filter = Path.GetFileName(file.Path);
            ManualResetEvent unblockHandler = new ManualResetEvent(false);
            watcher.Changed += (o, e) =>
            {
                // block the handling thread
                unblockHandler.WaitOne();
            };

            AutoResetEvent eventOccurred = new AutoResetEvent(false);
            watcher.Error += (o, e) =>
            {
                eventOccurred.Set();
            };
            watcher.EnableRaisingEvents = true;

            // FSW works by calling ReadDirectoryChanges aynchronously, processing the changes
            // in the callback and invoking event handlers from the callback serially.
            // After it processes all events for a particular callback it calls ReadDirectoryChanges
            // to queue another overlapped operation.
            // PER MSDN:
            //   When you first call ReadDirectoryChangesW, the system allocates a buffer to store change
            //   information. This buffer is associated with the directory handle until it is closed and 
            //   its size does not change during its lifetime. Directory changes that occur between calls
            //   to this function are added to the buffer and then returned with the next call. If the 
            //   buffer overflows, the entire contents of the buffer are discarded, the lpBytesReturned 
            //   parameter contains zero, and the ReadDirectoryChangesW function fails with the error 
            //   code ERROR_NOTIFY_ENUM_DIR.
            // We can force the error by increasing the amount of time between calls to ReadDirectoryChangesW
            // By blocking in an event handler, we allow the main thread of our test to generate a ton
            // of change events and overflow the OS's buffer.

            // We could copy the result of the operation and immediately call ReadDirectoryChangesW to 
            // limit the amount of time where we rely on the OS's buffer.  The downside of doing so 
            // is it can allow memory to grow out of control.

            // FSW tries to mitigate this by exposing InternalBufferSize.  The OS uses this when allocating
            // it's internal buffer (up to some limit).  Our docs say that limit is 64KB but testing on Win8.1 
            // indicates that it is much higher than this: I could grow the buffer up to 128 MB and still see
            // that it had an effect.  The size needed per operation is determined by the struct layout of 
            // FILE_NOTIFY_INFORMATION.  This works out to 16 + 2 * (filePath.Length + 1) bytes, where filePath
            // is the path to changed file relative to the path passed into ReadDirectoryChanges.

            // At some point we might decide to improve how FSW handles this at which point we'll need
            // a better test for Error (perhaps just a mock), but for now there is some value in forcing this limit.

            int internalBufferOperationCapacity = watcher.InternalBufferSize / (12 + 2 * (file.Path.Length + 1));

            // generate enough file change events to overflow the buffer
            // 4x is an approximation that should force the overflow.
            for (int i = 1; i < internalBufferOperationCapacity * 4; i++)
            {
                File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(i));
            }

            unblockHandler.Set();

            Utility.ExpectEvent(eventOccurred, "error");
        }
    }
示例#48
0
        private static WavechartBox show(String title, bool hold, params Tuple <Signal, int>[] series)
        {
            WavechartBox form       = null;
            Thread       formThread = null;

            AutoResetEvent stopWaitHandle = new AutoResetEvent(false);

            formThread = new Thread(() =>
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                // Show control in a form
                form            = new WavechartBox();
                form.Text       = title;
                form.formThread = formThread;

                if (!String.IsNullOrEmpty(title))
                {
                    form.zedGraphControl.GraphPane.Title.IsVisible = true;
                    form.zedGraphControl.GraphPane.Title.Text      = title;
                }

                var sequence = new ColorSequenceCollection(series.Length);

                for (int i = 0; i < series.Length; i++)
                {
                    var signal  = series[i].Item1;
                    int channel = series[i].Item2;

                    ComplexSignal complex = signal as ComplexSignal;

                    if (complex != null && complex.Status != ComplexSignalStatus.Normal)
                    {
                        double[] spectrum    = Accord.Audio.Tools.GetPowerSpectrum(complex.GetChannel(channel));
                        double[] frequencies = Accord.Audio.Tools.GetFrequencyVector(signal.Length, signal.SampleRate);

                        form.series.Add(new LineItem(i.ToString(), frequencies,
                                                     spectrum, sequence.GetColor(i), SymbolType.None));

                        form.zedGraphControl.GraphPane.XAxis.Title.Text = "Frequency";
                        form.zedGraphControl.GraphPane.YAxis.Title.Text = "Power";
                    }
                    else
                    {
                        double[] values;
                        if (signal.Channels == 1)
                        {
                            values = signal.ToDouble();
                        }
                        else
                        {
                            ExtractChannel extract = new ExtractChannel(channel);
                            values = extract.Apply(signal).ToDouble();
                        }

                        form.series.Add(new LineItem(i.ToString(), Vector.Range(0, signal.Length).ToDouble(),
                                                     values, sequence.GetColor(i), SymbolType.None));

                        form.zedGraphControl.GraphPane.XAxis.Title.Text = "Time";
                        form.zedGraphControl.GraphPane.YAxis.Title.Text = "Amplitude";
                    }
                }

                form.zedGraphControl.GraphPane.AxisChange();

                stopWaitHandle.Set();

                Application.Run(form);
            });

            formThread.SetApartmentState(ApartmentState.STA);

            formThread.Start();

            stopWaitHandle.WaitOne();

            if (!hold)
            {
                formThread.Join();
            }

            return(form);
        }
示例#49
0
    /// <summary>
    /// 
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="arguments"></param>
    /// <param name="timeout"></param>
    /// <param name="strStatus"></param>
    /// <returns></returns>
    public static int StartProcess(string filename, string arguments, Int32 timeout, ref string strStatus)
    {
        int intExitCode = 0;
        using (Process process = new Process())
        {
            process.StartInfo.FileName = filename;
            process.StartInfo.Arguments = arguments;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;

            StringBuilder output = new StringBuilder();
            StringBuilder error = new StringBuilder();

            using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
            using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
            {
                process.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        output.AppendLine(e.Data);
                    }
                };
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        error.AppendLine(e.Data);
                    }
                };

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                if (process.WaitForExit(timeout) &&
                    outputWaitHandle.WaitOne(timeout) &&
                    errorWaitHandle.WaitOne(timeout))
                {
                    // Process completed. Check process.ExitCode here.
                    intExitCode = process.ExitCode;
                }
                else
                {
                    // Timed out.
                    intExitCode = -2;
                }
                strStatus = output.ToString() + "\n" + error.ToString();
                strStatus = strStatus.Trim();
            }
        }
        return intExitCode;
    }
示例#50
0
 public void Dispose()
 {
     m_Disposing = true;
     m_Signal.Set();
 }
示例#51
0
 public void SendEvent()
 {
     sendEvent.Set();
 }
示例#52
0
        public static void ConvertHtmlToPdf(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput)
        {
            if (environment == null)
            {
                environment = Environment;
            }

            if (document.Html != null)
            {
                document.Url = "-";
            }

            String outputPdfFilePath;
            bool   delete;

            if (woutput.OutputFilePath != null)
            {
                outputPdfFilePath = woutput.OutputFilePath;
                delete            = false;
            }
            else
            {
                outputPdfFilePath = Path.Combine(environment.TempFolderPath, String.Format("{0}.pdf", Guid.NewGuid()));
                delete            = true;
            }

            if (!File.Exists(environment.WkHtmlToPdfPath))
            {
                throw new PdfConvertException(String.Format("File '{0}' not found. Check if wkhtmltopdf application is installed.", environment.WkHtmlToPdfPath));
            }

            StringBuilder paramsBuilder = new StringBuilder();

            paramsBuilder.Append("--page-size A4 ");

            if (!string.IsNullOrEmpty(document.HeaderUrl))
            {
                paramsBuilder.AppendFormat("--header-html {0} ", document.HeaderUrl);
                paramsBuilder.Append("--margin-top 25 ");
                paramsBuilder.Append("--header-spacing 5 ");
            }
            if (!string.IsNullOrEmpty(document.FooterUrl))
            {
                paramsBuilder.AppendFormat("--footer-html {0} ", document.FooterUrl);
                paramsBuilder.Append("--margin-bottom 25 ");
                paramsBuilder.Append("--footer-spacing 5 ");
            }

            if (!string.IsNullOrEmpty(document.HeaderLeft))
            {
                paramsBuilder.AppendFormat("--header-left \"{0}\" ", document.HeaderLeft);
            }

            if (!string.IsNullOrEmpty(document.HeaderCenter))
            {
                paramsBuilder.AppendFormat("--header-center \"{0}\" ", document.HeaderCenter);
            }

            if (!string.IsNullOrEmpty(document.HeaderRight))
            {
                paramsBuilder.AppendFormat("--header-right \"{0}\" ", document.HeaderRight);
            }

            if (!string.IsNullOrEmpty(document.FooterLeft))
            {
                paramsBuilder.AppendFormat("--footer-left \"{0}\" ", document.FooterLeft);
            }

            if (!string.IsNullOrEmpty(document.FooterCenter))
            {
                paramsBuilder.AppendFormat("--footer-center \"{0}\" ", document.FooterCenter);
            }

            if (!string.IsNullOrEmpty(document.FooterRight))
            {
                paramsBuilder.AppendFormat("--footer-right \"{0}\" ", document.FooterRight);
            }

            if (document.ExtraParams != null)
            {
                foreach (var extraParam in document.ExtraParams)
                {
                    paramsBuilder.AppendFormat("--{0} {1} ", extraParam.Key, extraParam.Value);
                }
            }

            if (document.Cookies != null)
            {
                foreach (var cookie in document.Cookies)
                {
                    paramsBuilder.AppendFormat("--cookie {0} {1} ", cookie.Key, cookie.Value);
                }
            }

            paramsBuilder.AppendFormat("\"{0}\" \"{1}\"", document.Url, outputPdfFilePath);

            try
            {
                StringBuilder output = new StringBuilder();
                StringBuilder error  = new StringBuilder();

                using (Process process = new Process())
                {
                    process.StartInfo.FileName               = environment.WkHtmlToPdfPath;
                    process.StartInfo.Arguments              = paramsBuilder.ToString();
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = true;
                    process.StartInfo.RedirectStandardInput  = true;

                    using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
                        using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                        {
                            DataReceivedEventHandler outputHandler = (sender, e) =>
                            {
                                if (e.Data == null)
                                {
                                    outputWaitHandle.Set();
                                }
                                else
                                {
                                    output.AppendLine(e.Data);
                                }
                            };

                            DataReceivedEventHandler errorHandler = (sender, e) =>
                            {
                                if (e.Data == null)
                                {
                                    errorWaitHandle.Set();
                                }
                                else
                                {
                                    error.AppendLine(e.Data);
                                }
                            };

                            process.OutputDataReceived += outputHandler;
                            process.ErrorDataReceived  += errorHandler;

                            try
                            {
                                process.Start();

                                process.BeginOutputReadLine();
                                process.BeginErrorReadLine();

                                if (document.Html != null)
                                {
                                    using (var stream = process.StandardInput)
                                    {
                                        byte[] buffer = Encoding.UTF8.GetBytes(document.Html);
                                        stream.BaseStream.Write(buffer, 0, buffer.Length);
                                        stream.WriteLine();
                                    }
                                }

                                if (process.WaitForExit(environment.Timeout) && outputWaitHandle.WaitOne(environment.Timeout) && errorWaitHandle.WaitOne(environment.Timeout))
                                {
                                    if (process.ExitCode != 0 && !File.Exists(outputPdfFilePath))
                                    {
                                        throw new PdfConvertException(String.Format("Html to PDF conversion of '{0}' failed. Wkhtmltopdf output: \r\n{1}", document.Url, error));
                                    }
                                }
                                else
                                {
                                    if (!process.HasExited)
                                    {
                                        process.Kill();
                                    }

                                    throw new PdfConvertTimeoutException();
                                }
                            }
                            finally
                            {
                                process.OutputDataReceived -= outputHandler;
                                process.ErrorDataReceived  -= errorHandler;
                            }
                        }
                }


                if (woutput.OutputStream != null)
                {
                    using (Stream fs = new FileStream(outputPdfFilePath, FileMode.Open))
                    {
                        byte[] buffer = new byte[32 * 1024];
                        int    read;

                        while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            woutput.OutputStream.Write(buffer, 0, read);
                        }
                    }
                }

                if (woutput.OutputCallback != null)
                {
                    byte[] pdfFileBytes = File.ReadAllBytes(outputPdfFilePath);
                    woutput.OutputCallback(document, pdfFileBytes);
                }
            }
            finally
            {
                if (delete && File.Exists(outputPdfFilePath))
                {
                    File.Delete(outputPdfFilePath);
                }
            }
        }
示例#53
0
文件: Program.cs 项目: BFMS/BFMS
    public static void Main()
    {
        // TODO:// replace with your app details and Betfair username/password
           BetfairClient client = new BetfairClient(Exchange.UK);
        client.Login( "nur1euro", "niedero", "nur1euro");

        // find all the upcoming UK horse races (EventTypeId 7)
        var marketFilter = new MarketFilter();
        marketFilter.EventTypeIds = new HashSet<string>() { "7" };
        marketFilter.MarketStartTime = new TimeRange()
        {
            From = DateTime.Now,
            To = DateTime.Now.AddDays(1)
        };
        marketFilter.MarketTypeCodes = new HashSet<String>() { "WIN" };
        var eventTypes = client.ListEventTypes(marketFilter);

        Console.WriteLine("BetfairClient.ListTimeRanges()");
        var timeRanges = client.ListTimeRanges(marketFilter, TimeGranularity.HOURS).Result;
        if (timeRanges.HasError)
            throw new ApplicationException();

          var marketCatalogues = client.ListMarketCatalogue(
            BFUtil.HorseRaceFilter("GB"),
            BFUtil.HorseRaceProjection(),
            MarketSort.FIRST_TO_START,
            100).Result.Response;

        marketCatalogues.ForEach(c =>
        {
            //Markets.Enqueue(c);
            List<String> marketIdList = new List<string>();
            marketIdList.Add(c.MarketId);
            OrderProjection orderProjection = OrderProjection.ALL;
            MatchProjection matchProjection = MatchProjection.NO_ROLLUP;

            var marketBook = client.ListMarketBook(
                marketIdList,
                BFUtil.HorseRacePriceProjection(),
                orderProjection,
                matchProjection
            ).Result.Response;
            Console.WriteLine(BFUtil.checkMarket(c, marketBook[0]));
            //Console.WriteLine(c.MarketName);
        });
        Console.WriteLine();

        var marketListener = MarketListener.Create(client, BFUtil.HorseRacePriceProjection(), 1);

        //while (Markets.Count > 0)
        //{
            AutoResetEvent waitHandle = new AutoResetEvent(false);
            MarketCatalogue marketCatalogue;
            Markets.TryDequeue(out marketCatalogue);

            var marketSubscription = marketListener.SubscribeMarketBook(marketCatalogue.MarketId)
                .SubscribeOn(Scheduler.Default)
                .Subscribe(
                tick =>
                {
                    Console.WriteLine(BFUtil.MarketBookConsole(marketCatalogue, tick, marketCatalogue.Runners));
                },
                () =>
                {
                    Console.WriteLine("Market finished");
                    waitHandle.Set();
                });

            waitHandle.WaitOne();
            marketSubscription.Dispose();
        //}

        Console.WriteLine("done.");
        Console.ReadLine();
    }
示例#54
0
 public void Stop()
 {
     m_stop = true;
     m_event.Set();
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="e"></param>
 public void AddReq(CacheEntry e)
 {
     //lock (queue)
     queue.Enqueue(e);
     ev.Set();
 }
示例#56
0
        private string ExtractTextFromAudio(string targetFile, int delayInMilliseconds)
        {
            var output = new StringBuilder();
            var path = Path.Combine(Configuration.DataDirectory, "pocketsphinx");
            var fileName = Path.Combine(path, "bin", "Release", "Win32", "pocketsphinx_continuous.exe");
            var hmm = Path.Combine(path, "model", "en-us", "en-us");
            var lm = Path.Combine(path, "model", "en-us", "en-us.lm.bin");
            var dict = Path.Combine(path, "model", "en-us", "cmudict-en-us.dict");
            var pocketPhinxParams = $"-infile \"{targetFile}\" -hmm \"{hmm}\" -lm \"{lm}\" -dict \"{dict}\" -time yes"; // > \"{_resultFile}\"";

            var process = new Process { StartInfo = new ProcessStartInfo(fileName, pocketPhinxParams) { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden } };
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.UseShellExecute = false;

            using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
            using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
            {
                process.OutputDataReceived += (sender, e) =>
                {
                    if (_abort)
                    {
                        return;
                    }

                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        output.AppendLine(e.Data);
                        var seconds = GetLastTimeStampInSeconds(e.Data);
                        if (seconds > 0)
                        {
                            _backgroundWorker.ReportProgress(seconds);
                        }
                        _backgroundWorker.ReportProgress(LogOutput, e.Data);
                    }
                };
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (_abort)
                    {
                        return;
                    }

                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        _backgroundWorker.ReportProgress(LogInfo, e.Data);
                    }
                };

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                var killed = false;
                while (!process.HasExited)
                {
                    Application.DoEvents();
                    Thread.Sleep(50);
                    if (_abort && !killed)
                    {
                        process.Kill();
                        killed = true;
                    }
                }

            }
            return output.ToString();
        }
示例#57
0
        internal void SetIoc(DataPipe pipe)
        {
            ClientTcpReceiver tcpReceiver = (ClientTcpReceiver)pipe[0];

            tcpReceiver.AddChannel(this);
            lock ( ConnectionLock )
            {
                if (!Client.Searcher.Contains(this))
                {
                    return;
                }

                Client.Searcher.Remove(this);
                SID = 0;

                ioc = tcpReceiver;
                lock (ioc.ChannelSID)
                {
                    // Console.WriteLine(ioc.ChannelSID.Count) ;
                    // Channel already known
                    if (ioc.ChannelSID.ContainsKey(ChannelName))
                    {
                        SID = ioc.ChannelSID[ChannelName];
                        // Console.WriteLine("Here") ;
                        Channel chan = ioc.ConnectedChannels.FirstOrDefault(
                            row =>
                            row.ChannelName == ChannelName &&
                            row.ChannelDataCount != 0
                            );
                        if (chan != null)
                        {
                            this.ChannelDataCount   = chan.ChannelDataCount;
                            this.channelDefinedType = chan.channelDefinedType;
                            this.ChannelDataCount   = chan.ChannelDataCount;
                            this.channelDefinedType = chan.ChannelDefinedType;
                            Status = ChannelStatus.CONNECTED;
                            ConnectionEvent.Set();
                        }
                    }
                }
            }
            if (SID != 0)
            {
                // Console.WriteLine("SID " + SID + " STATUS CHANGED") ;
                StatusChanged?.Invoke(this, Status);
                return;
            }
            if (Client.Configuration.DebugTiming)
            {
                lock ( ElapsedTimings )
                {
                    if (!ElapsedTimings.ContainsKey("IocConnection"))
                    {
                        ElapsedTimings.Add(
                            "IocConnection",
                            Stopwatch.Elapsed
                            );
                    }
                }
            }

            // We need to create the channel
            int padding;

            if (ChannelName.Length % 8 == 0)
            {
                padding = 8;
            }
            else
            {
                padding = (
                    8
                    - (ChannelName.Length % 8)
                    );
            }

            DataPacket packet = DataPacket.Create(
                16 + ChannelName.Length + padding
                );

            packet.Command    = (ushort)CommandID.CA_PROTO_CREATE_CHAN;
            packet.DataType   = 0;
            packet.DataCount  = 0;
            packet.Parameter1 = cid;
            packet.Parameter2 = (uint)CAConstants.CA_MINOR_PROTOCOL_REVISION;
            packet.SetDataAsString(ChannelName);

            if (ioc != null)
            {
                ioc.Send(packet);
            }
            else
            {
                Disconnect();
                return;
            }

            lock ( ElapsedTimings )
            {
                if (!ElapsedTimings.ContainsKey("SendCreateChannel"))
                {
                    ElapsedTimings.Add(
                        "SendCreateChannel",
                        Stopwatch.Elapsed
                        );
                }
            }
        }
示例#58
0
        public static void BasicLockTest()
        {
            var trwl = new TestReaderWriterLock();
            TestLockCookie tlc;
            var threadReady = new AutoResetEvent(false);
            var continueThread = new AutoResetEvent(false);
            Action checkForThreadErrors, waitForThread;
            Thread t =
                ThreadTestHelpers.CreateGuardedThread(out checkForThreadErrors, out waitForThread, () =>
                {
                    TestLockCookie tlc2;
                    Action switchToMainThread =
                        () =>
                        {
                            threadReady.Set();
                            continueThread.CheckedWait();
                        };

                    switchToMainThread();

                    // Multiple readers from multiple threads
                    {
                        trwl.AcquireReaderLock();
                        trwl.AcquireReaderLock();
                        switchToMainThread();
                        trwl.ReleaseReaderLock();
                        switchToMainThread();
                        trwl.ReleaseReaderLock();
                        switchToMainThread();

                        trwl.AcquireReaderLock();
                        trwl.ReleaseReaderLock();
                        switchToMainThread();
                    }

                    // What can be done when a read lock is held
                    {
                        trwl.AcquireReaderLock();
                        switchToMainThread();

                        // Any thread can take a read lock
                        trwl.AcquireReaderLock();
                        trwl.ReleaseReaderLock();
                        switchToMainThread();

                        // No thread can take a write lock
                        trwl.AcquireWriterLock(TimeoutExceptionHResult);
                        trwl.AcquireReaderLock();
                        trwl.UpgradeToWriterLock(TimeoutExceptionHResult);
                        trwl.ReleaseReaderLock();
                        switchToMainThread();

                        trwl.ReleaseReaderLock();
                        switchToMainThread();

                        // Owning thread releases read lock when upgrading
                        trwl.AcquireWriterLock();
                        trwl.ReleaseWriterLock();
                        switchToMainThread();

                        // Owning thread cannot upgrade if there are other readers or writers
                        trwl.AcquireReaderLock();
                        switchToMainThread();
                        trwl.ReleaseReaderLock();
                        trwl.AcquireWriterLock();
                        switchToMainThread();
                        trwl.ReleaseWriterLock();
                        switchToMainThread();
                    }

                    // What can be done when a write lock is held
                    {
                        // Write lock acquired through AcquireWriteLock is exclusive
                        trwl.AcquireWriterLock();
                        switchToMainThread();
                        trwl.ReleaseWriterLock();
                        switchToMainThread();

                        // Write lock acquired through upgrading is also exclusive
                        trwl.AcquireReaderLock();
                        tlc2 = trwl.UpgradeToWriterLock();
                        switchToMainThread();
                        trwl.DowngradeFromWriterLock(tlc2);
                        trwl.ReleaseReaderLock();
                        switchToMainThread();

                        // Write lock acquired through restore is also exclusive
                        trwl.AcquireWriterLock();
                        tlc = trwl.ReleaseLock();
                        trwl.RestoreLock(tlc);
                        switchToMainThread();
                        trwl.ReleaseWriterLock();
                        switchToMainThread();
                    }
                });
            t.IsBackground = true;
            t.Start();

            Action beginSwitchToBackgroundThread = () => continueThread.Set();
            Action endSwitchToBackgroundThread =
                () =>
                {
                    try
                    {
                        threadReady.CheckedWait();
                    }
                    finally
                    {
                        checkForThreadErrors();
                    }
                };
            Action switchToBackgroundThread =
                () =>
                {
                    beginSwitchToBackgroundThread();
                    endSwitchToBackgroundThread();
                };
            endSwitchToBackgroundThread();

            // Multiple readers from muliple threads
            {
                trwl.AcquireReaderLock();
                trwl.AcquireReaderLock();
                switchToBackgroundThread(); // AcquireReaderLock * 2
                trwl.ReleaseReaderLock();
                switchToBackgroundThread(); // ReleaseReaderLock

                // Release/restore the read lock while a read lock is held by another thread
                tlc = trwl.ReleaseLock();
                trwl.RestoreLock(tlc);

                switchToBackgroundThread(); // ReleaseReaderLock

                // Downgrade to read lock allows another thread to acquire read lock
                tlc = trwl.UpgradeToWriterLock();
                trwl.DowngradeFromWriterLock(tlc);
                switchToBackgroundThread(); // AcquireReaderLock, ReleaseReaderLock

                trwl.ReleaseReaderLock();
            }

            // What can be done when a read lock is held
            {
                switchToBackgroundThread(); // AcquireReaderLock
                {
                    // Any thread can take a read lock
                    trwl.AcquireReaderLock();
                    trwl.ReleaseReaderLock();
                    switchToBackgroundThread(); // same as above

                    // No thread can take a write lock
                    trwl.AcquireWriterLock(TimeoutExceptionHResult);
                    trwl.AcquireReaderLock();
                    trwl.UpgradeToWriterLock(TimeoutExceptionHResult);
                    switchToBackgroundThread(); // same as above
                    trwl.ReleaseReaderLock();

                    // Other threads cannot upgrade to a write lock, but the owning thread can
                    trwl.AcquireReaderLock();
                    trwl.UpgradeToWriterLock(TimeoutExceptionHResult);
                    trwl.ReleaseReaderLock();
                }
                switchToBackgroundThread(); // ReleaseReaderLock

                // Owning thread releases read lock when upgrading
                trwl.AcquireReaderLock();
                beginSwitchToBackgroundThread(); // AcquireWriterLock: background thread gets blocked
                trwl.UpgradeToWriterLock(); // unblocks background thread: ReleaseWriterLock
                trwl.ReleaseWriterLock();
                endSwitchToBackgroundThread();

                // Owning thread cannot upgrade if there are other readers or writers
                trwl.AcquireReaderLock();
                switchToBackgroundThread(); // AcquireReaderLock
                trwl.UpgradeToWriterLock(TimeoutExceptionHResult);
                trwl.ReleaseReaderLock();
                switchToBackgroundThread(); // ReleaseReaderLock, AcquireWriterLock
                trwl.UpgradeToWriterLock(TimeoutExceptionHResult);
                switchToBackgroundThread(); // ReleaseWriterLock
            }

            // What can be done when a write lock is held
            {
                trwl.AcquireWriterLock();
                TestLockCookie restoreToWriteLockTlc = trwl.ReleaseLock();
                Action verifyCannotAcquireLock =
                    () =>
                    {
                        trwl.AcquireReaderLock(TimeoutExceptionHResult);
                        trwl.AcquireWriterLock(TimeoutExceptionHResult);
                        trwl.UpgradeToWriterLock(TimeoutExceptionHResult);
                    };
                Action verifyCanAcquireLock =
                    () =>
                    {
                        trwl.AcquireReaderLock();
                        tlc = trwl.UpgradeToWriterLock();
                        trwl.DowngradeFromWriterLock(tlc);
                        trwl.ReleaseReaderLock();
                        trwl.AcquireWriterLock();
                        trwl.ReleaseWriterLock();
                        trwl.RestoreLock(restoreToWriteLockTlc.Clone());
                        trwl.ReleaseWriterLock();
                    };

                // Write lock acquired through AcquireWriteLock is exclusive
                switchToBackgroundThread(); // AcquireWriterLock
                verifyCannotAcquireLock();
                switchToBackgroundThread(); // ReleaseWriterLock
                verifyCanAcquireLock();

                // Write lock acquired through upgrading is also exclusive
                switchToBackgroundThread(); // AcquireReaderLock, UpgradeToWriterLock
                verifyCannotAcquireLock();
                switchToBackgroundThread(); // DowngradeFromWriterLock, ReleaseReaderLock
                verifyCanAcquireLock();

                // Write lock acquired through restore is also exclusive
                switchToBackgroundThread(); // AcquireWriterLock, ReleaseLock, RestoreLock
                verifyCannotAcquireLock();
                switchToBackgroundThread(); // ReleaseWriterLock
                verifyCanAcquireLock();
            }

            beginSwitchToBackgroundThread();
            waitForThread();
            trwl.Dispose();
        }
        public static async Task <String> GetCLIOutputAsync(string solutionDir)
        {
            String strAppPath  = GetAssemblyLocalPathFrom(typeof(MainPanelCommand));
            String strFilePath = Path.Combine(strAppPath, "Resources");
            String pathToCli   = Path.Combine(strFilePath, "jfrog.exe");
            await OutputLog.ShowMessageAsync("Path for the JFrog CLI: " + pathToCli);

            //Create process
            Process pProcess = new System.Diagnostics.Process();

            // strCommand is path and file name of command to run
            pProcess.StartInfo.FileName = pathToCli;

            // strCommandParameters are parameters to pass to program
            // Here we will run the nuget command for the cli
            pProcess.StartInfo.Arguments = "rt nuget-deps-tree";

            pProcess.StartInfo.UseShellExecute = false;
            pProcess.StartInfo.CreateNoWindow  = true;
            // Set output of program to be written to process output stream
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.RedirectStandardError  = true;
            pProcess.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
            pProcess.StartInfo.WorkingDirectory       = solutionDir;

            StringBuilder strOutput = new StringBuilder();
            StringBuilder error     = new StringBuilder();

            // Saving the response from the CLI to a StringBuilder.
            using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
                using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                {
                    // Get program output
                    // The json returned from the CLI
                    pProcess.OutputDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            outputWaitHandle.Set();
                        }
                        else
                        {
                            strOutput.AppendLine(e.Data);
                        }
                    };
                    pProcess.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            errorWaitHandle.Set();
                        }
                        else
                        {
                            error.AppendLine(e.Data);
                        }
                    };

                    // Start the process
                    pProcess.Start();
                    pProcess.BeginOutputReadLine();
                    pProcess.BeginErrorReadLine();
                    pProcess.WaitForExit();

                    // Wait for the entire output to be written
                    if (outputWaitHandle.WaitOne(2) &&
                        errorWaitHandle.WaitOne(2))
                    {
                        // Process completed. Check process.ExitCode here.
                        if (pProcess.ExitCode != 0)
                        {
                            string message = "Failed to get CLI output. Exit code: " + pProcess.ExitCode + " Returned error:" + error.ToString();
                            throw new IOException(message);
                        }
                        if (!string.IsNullOrEmpty(error.ToString()))
                        {
                            await OutputLog.ShowMessageAsync(error.ToString());
                        }
                        // Returning the output from the CLI that is the json itself.
                        return(strOutput.ToString());
                    }
                    else
                    {
                        // Timed out.
                        await OutputLog.ShowMessageAsync("Process timeout");

                        throw new IOException("Process timeout, please run the following command from the solution directory and send us the output:" + pathToCli + " rt ndt");
                    }
                }
        }
示例#60
0
 public void Enqueue(Action action)
 {
     actions.Enqueue(action);
     messageArrived.Set();
 }