Inheritance: EventWaitHandle
Beispiel #1
2
 public WaitForAll(AsyncCallback callbackWhenOver, object asyncState)
 {
     callbackResults = new Dictionary<string, IAsyncResult>();
     this.callbackWhenOver = callbackWhenOver;
     this.asyncState = asyncState;
     handle = new AutoResetEvent(false);
 }
            internal AnalysisQueue(VsProjectAnalyzer analyzer) {
                _workEvent = new AutoResetEvent(false);
                _cancel = new CancellationTokenSource();
                _analyzer = analyzer;

                // save the analysis once it's ready, but give us a little time to be
                // initialized and start processing stuff...
                _lastSave = DateTime.Now - _SaveAnalysisTime + TimeSpan.FromSeconds(10);

                _queue = new List<IAnalyzable>[PriorityCount];
                for (int i = 0; i < PriorityCount; i++) {
                    _queue[i] = new List<IAnalyzable>();
                }
                _enqueuedGroups = new HashSet<IGroupableAnalysisProject>();

                _workThread = new Thread(Worker);
                _workThread.Name = "Node.js Analysis Queue";
                _workThread.Priority = ThreadPriority.BelowNormal;
                _workThread.IsBackground = true;

                // start the thread, wait for our synchronization context to be created
                using (AutoResetEvent threadStarted = new AutoResetEvent(false)) {
                    _workThread.Start(threadStarted);
                    threadStarted.WaitOne();
                }
            }
Beispiel #3
1
		// Initialize Parallel class's instance creating required number of threads
		// and synchronization objects
		private void Initialize( )
		{
			threadsCount = System.Environment.ProcessorCount;
			
			//No point starting new threads for a single core computer
			if (threadsCount <= 1) {
				return;
			}
			
			// array of events, which signal about available job
			jobAvailable = new AutoResetEvent[threadsCount];
			// array of events, which signal about available thread
			threadIdle = new ManualResetEvent[threadsCount];
			// array of threads
			threads = new Thread[threadsCount];
		
			for ( int i = 0; i < threadsCount; i++ )
			{
				jobAvailable[i] = new AutoResetEvent( false );
				threadIdle[i]   = new ManualResetEvent( true );
		
				threads[i] = new Thread( new ParameterizedThreadStart( WorkerThread ) );
				threads[i].IsBackground = false;
				threads[i].Start( i );
			}
		}
Beispiel #4
0
        public multi_downloader(string[] files, string dest_dir, System.Threading.AutoResetEvent resetEvent, int threads = -1)
        {
            this.files      = files;
            this.dest_dir   = dest_dir;
            this.resetEvent = resetEvent;
            started_count   = 0;
            parallel_count  = threads > 0 ? threads : parallel_count;

            downloader = new download_file[parallel_count];
            for (int i = 0; i < parallel_count; i++)
            {
                downloader[i] = new download_file(DestinationDir, i + 1);
                downloader[i].DownloadProgress  += new DownloadProgressHandler(download_progress);
                downloader[i].DownloadCompleted += new DownloadCompletedHandler(download_completed);
            }

            Console.WriteLine(string.Format(@"
  Downloader started.
  {0} files to be downloaded.
  Download directory: ""{1}""  
  Parallel in: {2} threads
  
  ============================

"
                                            , files.Count(), dest_dir, parallel_count));
        }
            /// <summary>
            /// Constructor
            /// </summary>
            /// <param name="action">Action</param>
            /// <param name="synchronizeWithUpdate">Whether to sync with the main thread update loop</param>
            internal EZThreadRunner(Action action, bool synchronizeWithUpdate)
            {
                this.action  = action;
                this.running = true;
                if (synchronizeWithUpdate)
                {
                    SyncEvent = new System.Threading.AutoResetEvent(true);
                }

#if TASK_AVAILABLE
                if (synchronizeWithUpdate)
                {
                    Task.Factory.StartNew(ThreadFunctionSync);
                }
                else
                {
                    Task.Factory.StartNew(ThreadFunction);
                }
#else
                WaitCallback w;
                if (synchronizeWithUpdate)
                {
                    w = new WaitCallback((s) => ThreadFunctionSync());
                }
                else
                {
                    w = new WaitCallback((s) => ThreadFunction());
                }
                ThreadPool.QueueUserWorkItem(w);
#endif
            }
        public void Promise_Reject_UserInfo()
        {
            var args = default(object[]);
            var are = new AutoResetEvent(false);
            var resolve = new MockCallback(_ => { });
            var reject = new MockCallback(a =>
            {
                args = a;
                are.Set();
            });
            var promise = new Promise(resolve, reject);

            var code = "42";
            var message = "foo";
            var e = new Exception();
            e.Data.Add("qux", "baz");
            promise.Reject(code, message, e);
            are.WaitOne();

            Assert.IsNotNull(args);
            Assert.AreEqual(1, args.Length);
            var json = args[0] as JObject;
            Assert.IsNotNull(json);
            var userInfo = json["userInfo"] as JObject;
            Assert.IsNotNull(userInfo);
            Assert.AreEqual("baz", userInfo["qux"]);
        }
        public void GetShopsByNameLowDetailRetrievalTest()
        {
            // ARANGE
            using (AutoResetEvent waitEvent = new AutoResetEvent(false))
            {
                ResultEventArgs<Shops> result = null;

                IShopService shopsService = new ShopService(new EtsyContext(NetsyData.EtsyApiKey));
                shopsService.GetShopsByNameCompleted += (s, e) =>
                {
                    result = e;
                    waitEvent.Set();
                };

                // ACT
                shopsService.GetShopsByName("fred", SortOrder.Up, 0, 10, DetailLevel.Low);
                bool signalled = waitEvent.WaitOne(NetsyData.WaitTimeout);

                // ASSERT
                // check that the event was fired, did not time out
                Assert.IsTrue(signalled, "Not signalled");

                // check the data
                TestHelpers.CheckResultSuccess(result);

                Assert.IsNotNull(result.ResultValue.Results);
                Assert.IsTrue(result.ResultStatus.Success);
                Assert.IsTrue(result.ResultValue.Count > 0);
            }
        }
        public void Start()
        {
            startedEvent = new AutoResetEvent(false);
            Thread t = new Thread(Execute);

            t.Start();
        }
Beispiel #9
0
		public Form2(String hostPort, Form1 form1)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
			dataReadyToSend = new AutoResetEvent(false);
			refToForm1 = form1;
			// Resolve the local host.
			IPHostEntry localHost = Dns.Resolve(Dns.GetHostName());
			// Create a local end point for listening.
			IPEndPoint localEndPoint = new IPEndPoint(localHost.AddressList[0], 4001);
			// Instantiate the TCP Listener.
			tcpListener = new TcpListener(localEndPoint);
			tcpListener.Start();
			tcp = tcpListener.AcceptTcpClient();
			ethernetThreadStart = new ThreadStart(this.ThreadProcPollOnEthernet);
			pollDevicesEthernetThread = new Thread(ethernetThreadStart);
			pollDevicesEthernetThread.Name = "Listener's Receive Thread";
			pollDevicesEthernetThread.ApartmentState = System.Threading.ApartmentState.MTA;
			pollDevicesEthernetThread.Start();
		}
        public void Send_to_standIn()
        {
            var cre = PubnubCredentials.LoadFrom("pubnub credentials.txt");
            using(var sut = new PubnubHostTransceiver(cre, "hostchannel"))
            {
                var standIn = new Pubnub(cre.PublishingKey, cre.SubscriptionKey, cre.SecretKey);
                try
                {
                    var standInChannel = Guid.NewGuid().ToString();

                    var are = new AutoResetEvent(false);
                    ReadOnlyCollection<object> result = null;
                    standIn.subscribe(standInChannel, (ReadOnlyCollection<object> _) =>
                                              {
                                                  result = _;
                                                  are.Set();
                                              });

                    var ho = new HostOutput{CorrelationId = Guid.NewGuid(), Data = "hello".Serialize(), Portname = "portname"};
                    sut.SendToStandIn(new Tuple<string, HostOutput>(standInChannel, ho));

                    Assert.IsTrue(are.WaitOne(5000));

                    var hoReceived = Convert.FromBase64String((string)((JValue)result[0]).Value).Deserialize() as HostOutput;
                    Assert.AreEqual(ho.CorrelationId, hoReceived.CorrelationId);
                    Assert.AreEqual(ho.Data, hoReceived.Data);
                    Assert.AreEqual(ho.Portname, hoReceived.Portname);
                }
                finally
                {
                    standIn.subscribe("standIn", _ => {});
                }
            }
        }
Beispiel #11
0
 static Reader()
 {
     Thread inputThread = new Thread(Run) {IsBackground = true};
     inputThread.Start();
     GetInput = new AutoResetEvent(false);
     GotInput = new AutoResetEvent(false);
 }
Beispiel #12
0
        public void DisconnectAsync_Success()
        {
            AutoResetEvent completed = new AutoResetEvent(false);

            IPEndPoint loopback = new IPEndPoint(IPAddress.Loopback, 0);
            using (var server1 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback))
            using (var server2 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback))
            {
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += OnCompleted;
                args.UserToken = completed;
                args.RemoteEndPoint = server1.EndPoint;
                args.DisconnectReuseSocket = true;

                using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    Assert.True(client.ConnectAsync(args));
                    completed.WaitOne();
                    Assert.Equal(SocketError.Success, args.SocketError);

                    Assert.True(client.DisconnectAsync(args));
                    completed.WaitOne();
                    Assert.Equal(SocketError.Success, args.SocketError);

                    args.RemoteEndPoint = server2.EndPoint;

                    Assert.True(client.ConnectAsync(args));
                    completed.WaitOne();
                    Assert.Equal(SocketError.Success, args.SocketError);
                }
            }
        }
        public void GetMethodTableCallTest()
        {
            // ARRANGE
            using (AutoResetEvent waitEvent = new AutoResetEvent(false))
            {
                ResultEventArgs<MethodTable> result = null;
                IServerService serverService = new ServerService(new EtsyContext(NetsyData.EtsyApiKey));
                serverService.GetMethodTableCompleted += (s, e) =>
                {
                    result = e;
                    waitEvent.Set();
                };

                // ACT
                serverService.GetMethodTable();
                bool signalled = waitEvent.WaitOne(Constants.WaitTimeout);

                // ASSERT
                // check that the event was fired, did not time out
                Assert.IsTrue(signalled, "Not signalled");

                // check the data
                Assert.IsNotNull(result);
                TestHelpers.CheckResultSuccess(result);

                Assert.IsTrue(result.ResultValue.Count > 1);
                Assert.IsTrue(result.ResultValue.Results.Length > 1);
                Assert.IsNull(result.ResultValue.Params);
            }
        }
        public void TestArbitrary()
        {
            AutoResetEvent are = new AutoResetEvent(false);
            var client = new AustinHarris.JsonRpc.JsonRpcClient(remoteUri);
            var arbitrary = new Newtonsoft.Json.Linq.JObject();
            JObject r = null;
            Exception e = null;
            for (int i = 0; i < 10; i++)
            {
                arbitrary[getPrintableString(10)] = getPrintableString(20);
                arbitrary[getNonPrintableString(10)] = getNonPrintableString(20);
                arbitrary[getExtendedAsciiString(10)] = getExtendedAsciiString(20);
            }

            var myObs = client.Invoke<Newtonsoft.Json.Linq.JObject>("testArbitraryJObject", arbitrary, Scheduler.TaskPool);

            using(myObs.Subscribe(
                onNext: (jo) =>
                {
                   r = jo.Result;
                },
                onError:   _ =>
                {
                    e = _;
                },
                onCompleted: () => are.Set()
                ))
            {
                are.WaitOne();
            };

            
            Assert.IsTrue(r.ToString() == arbitrary.ToString());
            Assert.IsTrue(e == null);
        }
        public void when_sending_message_with_session_then_session_receiver_gets_both_messages_fast()
        {
            var sender = this.Settings.CreateTopicClient(this.Topic);
            var signal = new AutoResetEvent(false);
            var body1 = Guid.NewGuid().ToString();
            var body2 = Guid.NewGuid().ToString();
            var stopWatch = new Stopwatch();

            var receiver = new SessionSubscriptionReceiver(this.Settings, this.Topic, this.Subscription);

            sender.Send(new BrokeredMessage(body1) { SessionId = "foo" });
            sender.Send(new BrokeredMessage(body2) { SessionId = "bar" });

            var received = new ConcurrentBag<string>();

            receiver.Start(
                m =>
                {
                    received.Add(m.GetBody<string>());
                    signal.Set();
                    return MessageReleaseAction.CompleteMessage;
                });

            signal.WaitOne();
            stopWatch.Start();
            signal.WaitOne();
            stopWatch.Stop();

            receiver.Stop();

            Assert.Contains(body1, received);
            Assert.Contains(body2, received);
            Assert.InRange(stopWatch.Elapsed, TimeSpan.Zero, TimeSpan.FromSeconds(2));
        }
Beispiel #16
0
        public void GetShopsByNameApiKeyInvalidTest()
        {
            // ARRANGE
            using (AutoResetEvent waitEvent = new AutoResetEvent(false))
            {
                ResultEventArgs<Shops> result = null;
                IShopService shopsService = new ShopService(new EtsyContext("InvalidKey"));
                shopsService.GetShopsByNameCompleted += (s, e) =>
                {
                    result = e;
                    waitEvent.Set();
                };

                // ACT
                shopsService.GetShopsByName("fred", SortOrder.Up, 0, 10, DetailLevel.Low);
                bool signalled = waitEvent.WaitOne(NetsyData.WaitTimeout);

                // ASSERT
                // check that the event was fired, did not time out
                Assert.IsTrue(signalled, "Not signalled");

                // check the data - should fail
                Assert.IsNotNull(result);
                Assert.IsNotNull(result.ResultStatus);
                Assert.IsFalse(result.ResultStatus.Success);
                Assert.AreEqual(WebExceptionStatus.ProtocolError, result.ResultStatus.WebStatus);
            }
        }
        public void ConsumeMessagesOnMultipleWorkerThreads()
        {
            const int NumerOfMessages = 1000;

            this.module.ConsumeDelay = TimeSpan.FromMilliseconds(0);
            this.testee = new ModuleController();
            this.testee.Initialize(this.module, 10);

            for (int i = 0; i < NumerOfMessages; i++)
            {
                this.testee.EnqueueMessage(i);
            }

            AutoResetEvent signal = new AutoResetEvent(false);
            int count = 0;
            object padlock = new object();
            this.testee.AfterConsumeMessage += delegate
                {
                    lock (padlock)
                    {
                        count++;
                        if (count == NumerOfMessages)
                        {
                            signal.Set();
                        }
                    }
                };

            this.testee.Start();

            Assert.IsTrue(signal.WaitOne(10000, false), "not all messages consumed. Consumed " + this.module.Messages.Count);
            this.testee.Stop();
        }
Beispiel #18
0
        private void EhThreadBody()
        {
            while (_keepThreadRunning)
            {
                try
                {
                    ProcessInvokerQueue();
                    _triggeringEvent.WaitOne(_safetyIntervalTime_msec);
                }
                catch (Exception ex)
                {
                    // the exception must be re-thrown on the Gui thread in order to be handled
                    _dispatcherForReThrowingExceptions.Invoke((Action <Exception>)ReThrow, new object[] { ex });
                }
            }

            // Process the invoker queue one last time
            ProcessInvokerQueue();

            var locTriggerEvent = _triggeringEvent;

            if (null != locTriggerEvent)
            {
                locTriggerEvent.Dispose();
            }

            _triggeringEvent = null;
            _thread          = null;
        }
Beispiel #19
0
 /// <summary>
 /// Constructs an Engine for the specified Debugger.
 /// </summary>
 /// <param name="debugger">Debugger instance.</param>
 public Engine(Debugger debugger)
 {
     Debugger = debugger;
     _pause = false;
     _stop = false;
     AllowedToContinue = new AutoResetEvent(false);
 }
        /// <summary>
        /// Default constructor, Instantiates a new copy of the TexturePipeline class
        /// </summary>
        /// <param name="client">Reference to the instantiated <see cref="GridClient"/> object</param>
        public TexturePipeline(GridClient client)
        {
            _Client = client;

            maxTextureRequests = client.Settings.MAX_CONCURRENT_TEXTURE_DOWNLOADS;

            resetEvents     = new AutoResetEvent[maxTextureRequests];
            threadpoolSlots = new int[maxTextureRequests];

            _Transfers = new Dictionary <UUID, TaskInfo>();

            // Pre-configure autoreset events and threadpool slots
            for (int i = 0; i < maxTextureRequests; i++)
            {
                resetEvents[i]     = new AutoResetEvent(true);
                threadpoolSlots[i] = -1;
            }

            // Handle client connected and disconnected events
            client.Network.LoginProgress += delegate(object sender, LoginProgressEventArgs e) {
                if (e.Status == LoginStatus.Success)
                {
                    Startup();
                }
            };

            client.Network.Disconnected += delegate { Shutdown(); };
        }
Beispiel #21
0
 /// <summary>
 /// Initialise a new channel.
 /// </summary>
 /// <param name="i">The backlog for this channel, or 0 for infinite.</param>
 public Channel(int i = 0)
 {
     backlog = i;
     queue   = new Queue <T>();
     reset   = new AutoResetEvent(false);
     resetR  = new AutoResetEvent(false);
 }
Beispiel #22
0
        public static void Main(string[] args)
        {
            var timeout = Int32.Parse(args[0]);

            var waitEvent = new System.Threading.AutoResetEvent(false);

            var hr = new HandlerRoutine(type =>
            {
                Console.WriteLine($"ConsoleCtrlHandler got signal: {type}");

                Console.WriteLine("Waiting for shutdown.");
                for (int countdown = 1; countdown <= timeout; countdown++)
                {
                    Console.WriteLine($"{countdown}");
                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));
                }

                Console.WriteLine("Done waiting - setting event and exiting.");

                waitEvent.Set();

                return(false);
            });

            SetConsoleCtrlHandler(hr, true);

            Console.WriteLine("Shutdown will wait {0} seconds.", timeout);
            Console.WriteLine("Waiting on handler to trigger");

            waitEvent.WaitOne();

            GC.KeepAlive(hr);
        }
        public void Should_be_able_to_do_basic_request_async()
        {
            const string expectedResult = "Sending back 'Ninja!!'";
            var autoResetEvent = new AutoResetEvent(false);

            bus.Respond<TestRequestMessage, TestResponseMessage>(request =>
            {
                var response = new TestResponseMessage
                {
                    Text = string.Format("Sending back '{0}'", request.Text)
                };
                return response;
            });

            var actualResult = string.Empty;

            using (var channel = bus.OpenPublishChannel())
            {
                var request = new TestRequestMessage { Text = "Ninja!!" };

                var responseTask = channel.RequestAsync<TestRequestMessage, TestResponseMessage>(request);

                responseTask.ContinueWith(t =>
                    {
                        actualResult = t.Result.Text;
                        autoResetEvent.Set();
                    });
            }

            // give the bus a chance to deliver the message
            autoResetEvent.WaitOne(1000);

            actualResult.ShouldEqual(expectedResult);
        }
Beispiel #24
0
        public int Run(PlayerOptions options)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            int res = Initialize(options);

            if (res != 0)
            {
                return(res);
            }

            if (!options.NonInteractive)
            {
                Console.WriteLine(StringResources.PressKeyToExit);
                Console.ReadKey();
            }
            else
            {
                m_IsDaemon = options.Daemon;
                m_NonInteractiveWaitEvent = new System.Threading.AutoResetEvent(false);
                bool shutdown = false;
                while (!shutdown)
                {
                    m_NonInteractiveWaitEvent.WaitOne(200);
                    lock (m_LockObject)
                    {
                        shutdown = m_Shutdown;
                    }
                }
            }

            Shutdown();
            return(0);
        }
        public void Should_not_overwrite_correlation_id()
        {
            var autoResetEvent = new AutoResetEvent(false);
            const string expectedCorrelationId = "abc_foo";
            var actualCorrelationId = "";

            var queue = EasyNetQ.Topology.Queue.DeclareDurable("myqueue");
            var exchange = EasyNetQ.Topology.Exchange.DeclareDirect("myexchange");
            queue.BindTo(exchange, "#");
            bus.Subscribe<MyMessage>(queue, (message, info) => Task.Factory.StartNew(() =>
            {
                actualCorrelationId = message.Properties.CorrelationId;
                autoResetEvent.Set();
            }));

            var messageToSend = new Message<MyMessage>(new MyMessage());
            messageToSend.Properties.CorrelationId = expectedCorrelationId;

            using (var channel = bus.OpenPublishChannel())
            {
                channel.Publish(exchange, "abc", messageToSend);
            }

            autoResetEvent.WaitOne(1000);

            actualCorrelationId.ShouldEqual(expectedCorrelationId);
        }
        private PriceDTO GetMarketInfo(int marketId)
        {
            IStreamingListener<PriceDTO> listener = null;
            PriceDTO marketInfo = null;

            try
            {
                listener = _streamingClient.BuildPricesListener(marketId);
                var gate = new AutoResetEvent(false);

                listener.MessageReceived += (o, s) =>
                                        {
                                            marketInfo = s.Data;
                                            gate.Set();
                                        };


                if (!gate.WaitOne(10000))
                {
                    throw new Exception("timed out waiting for market data");
                }
            }
            finally
            {
                _streamingClient.TearDownListener(listener);
            }

            return marketInfo;
        }
        protected void Test1(IDatagramEventSocket[] sockets, EndPoint[] endPoints)
        {
            byte[] sendData = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
            int recvIdx = -1, recvSize = -1;
            byte[] recvData = null;
            AutoResetEvent done = new AutoResetEvent (false);

            for (int i = 0; i < sockets.Length; i++) {
                sockets[i].Bind (endPoints[i]);
                sockets[i].Received += new DatagramReceiveEventHandler (delegate (object sender, DatagramReceiveEventArgs e) {
                    recvIdx = Array.IndexOf<IDatagramEventSocket> (sockets, sender as IDatagramEventSocket);
                    recvSize = e.Size;
                    recvData = (byte[])e.Buffer.Clone ();
                    done.Set ();
                });
            }

            for (int i = 0; i < sockets.Length; i++) {
                for (int k = 0; k < endPoints.Length; k++) {
                    sockets[i].SendTo (sendData, endPoints[k]);
                    done.WaitOne ();
                    Array.Resize<byte> (ref recvData, recvSize);
                    string id = "#" + (i + 1).ToString () + "." + (k + 1).ToString ();
                    Assert.AreEqual (k, recvIdx, id + ".1");
                    Assert.AreEqual (sendData.Length, recvSize, id + ".2");
                    Assert.AreEqual (sendData, recvData, id + ".3");
                }
            }
        }
Beispiel #28
0
        public async Task TestMICRenderURLScopeID()
        {
            // Arrange
            var    builder             = new Client.Builder(TestSetup.app_key, TestSetup.app_secret);
            var    client              = builder.Build();
            var    autoEvent           = new System.Threading.AutoResetEvent(false);
            string urlToTestForScopeID = String.Empty;

            var micDelegate = new KinveyMICDelegate <User>()
            {
                onError         = (user) => { },
                onSuccess       = (error) => { },
                onReadyToRender = (url) => {
                    urlToTestForScopeID = url;
                    autoEvent.Set();
                }
            };

            // Act
            User.LoginWithMIC("mytestredirectURI", micDelegate);

            bool signal = autoEvent.WaitOne(5000);

            // Assert
            Assert.IsTrue(signal);
            Assert.IsFalse(urlToTestForScopeID.Equals(string.Empty));
            Assert.IsTrue(urlToTestForScopeID.Contains("scope=openid"));
        }
        FacetedMesh MeshPrim(Primitive prim)
        {
            FacetedMesh mesh = null;

            if (prim.Sculpt == null || prim.Sculpt.SculptTexture == UUID.Zero)
            {
                mesh = Mesher.GenerateFacetedMesh(prim, DetailLevel.Highest);
            }
            else if (prim.Sculpt.Type != SculptType.Mesh)
            {
                Image img = null;
                if (LoadTexture(prim.Sculpt.SculptTexture, ref img, true))
                {
                    mesh = Mesher.GenerateFacetedSculptMesh(prim, (Bitmap)img, DetailLevel.Highest);
                }
            }
            else
            {
                var gotMesh = new System.Threading.AutoResetEvent(false);

                Client.Assets.RequestMesh(prim.Sculpt.SculptTexture, (success, meshAsset) =>
                {
                    if (!success || !FacetedMesh.TryDecodeFromAsset(prim, meshAsset, DetailLevel.Highest, out mesh))
                    {
                        Logger.Log("Failed to fetch or decode the mesh asset", Helpers.LogLevel.Warning, Client);
                    }
                    gotMesh.Set();
                });

                gotMesh.WaitOne(20 * 1000, false);
            }
            return(mesh);
        }
Beispiel #30
0
        public void AutoRestEventTest()
        {
            CodeTimer.Time("AutoResetEvent(false)", () =>//无信号,可以通过WaitOne 阻塞线程的执行,通过Set发出信号唤醒等待的线程
            {
                using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false))
                {
                    System.Threading.ThreadPool.QueueUserWorkItem((s) =>
                    {
                        Thread.Sleep(1000);
                        Console.WriteLine("Run!");
                        are.Set();
                    });
                    are.WaitOne();
                }
            });

            CodeTimer.Time("AutoResetEvent(true)", () =>//有信号表示终止状态,即线程属于闲置状态
            {
                using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(true))
                {
                    System.Threading.ThreadPool.QueueUserWorkItem((s) =>
                    {
                        Thread.Sleep(1000);
                        Console.WriteLine("Not Run!");
                        are.Set();
                    });
                    are.WaitOne();//不会等待子线程的结束
                }
            });
        }
Beispiel #31
0
        private bool m_disposed;                     // Whether or not this manager has been disposed

        //--//

        /// <summary>
        /// Creates and initializes a new BTManager
        /// </summary>
        protected BTManager(BTDriver driver, IPowerPolicy pp)
        {
            m_driver = null;

            try
            {
                m_driver = driver;
                m_pp = (null == pp) ? new DefaultPowerPolicy() : pp;

                m_outstandingConnections = new ArrayList();
                m_connectionsToBeProcessed = new ArrayList();
                m_newCommand = new AutoResetEvent(false);

                m_scheduler = new Thread(new ThreadStart(AggregateAndDispatch));
                m_scheduler.Start();

                m_disposed = false;
            }
            catch
            {
                m_disposed = true;

                throw;
            }

            // Now apply policy for no pending commands
            m_pp.ApplyPolicy(m_driver, null, null);
        }
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 /// <param name="events">the ResponseEvents to store the events in</param>
 /// <param name="actionCompleteEventClass">the type of event that indicates that all events have been received</param>
 /// <param name="thread">the thread to interrupt when the actionCompleteEventClass has been received</param>
 public ResponseEventHandler(ManagerConnection connection, ManagerActionEvent action, AutoResetEvent autoEvent)
 {
     this.connection = connection;
     this.events = new ResponseEvents();
     this.action = action;
     this.autoEvent = autoEvent;
 }
        public void GetMethodTableApiKeyInvalidTest()
        {
            // ARRANGE
            using (AutoResetEvent waitEvent = new AutoResetEvent(false))
            {
                ResultEventArgs<MethodTable> result = null;
                IServerService serverService = new ServerService(new EtsyContext("InvalidKey"));
                serverService.GetMethodTableCompleted += (s, e) =>
                {
                    result = e;
                    waitEvent.Set();
                };

                // ACT
                serverService.GetMethodTable();
                bool signalled = waitEvent.WaitOne(Constants.WaitTimeout);

                // ASSERT
                // check that the event was fired, did not time out
                Assert.IsTrue(signalled, "Not signalled");

                // check the data - should fail
                Assert.IsNotNull(result);
                Assert.IsNotNull(result.ResultStatus);
                Assert.IsFalse(result.ResultStatus.Success);
                Assert.AreEqual(WebExceptionStatus.ProtocolError, result.ResultStatus.WebStatus);
            }
        }
Beispiel #34
0
        public void Close()
        {
            try
            {
                try
                {
                    _sock.Shutdown(SocketShutdown.Both);
                }
                catch { }

                _sock.Close();
                _sock.Dispose();
                if (wait != null)
                {
                    wait.Close();
                    wait.Dispose();
                    wait = null;
                }

                AsynEvent.Dispose();
            }
            catch (ObjectDisposedException)
            {
            }
            catch (NullReferenceException)
            {
            }
        }
        public void Receive_from_standIn()
        {
            var cre = PubnubCredentials.LoadFrom("pubnub credentials.txt");
            using (var sut = new PubnubHostTransceiver(cre, "hostchannel"))
            {

                var are = new AutoResetEvent(false);
                HostInput result = null;
                sut.ReceivedFromStandIn += _ =>
                                               {
                                                   result = _;
                                                   are.Set();
                                               };

                var standIn = new Pubnub(cre.PublishingKey, cre.SubscriptionKey, cre.SecretKey);
                var hi = new HostInput{CorrelationId = Guid.NewGuid(), Data = "hello".Serialize(), Portname = "portname", StandInEndpointAddress = "endpoint"};
                standIn.publish("hostchannel", hi.Serialize(), _ => { });

                Assert.IsTrue(are.WaitOne(5000));

                Assert.AreEqual(hi.CorrelationId, result.CorrelationId);
                Assert.AreEqual(hi.Data, result.Data);
                Assert.AreEqual(hi.Portname, result.Portname);
                Assert.AreEqual(hi.StandInEndpointAddress, result.StandInEndpointAddress);
            }
        }
Beispiel #36
0
        internal ThreadManager(Debugger debugger)
        {
            this.debugger = debugger;

            thread_hash = Hashtable.Synchronized(new Hashtable());
            engine_hash = Hashtable.Synchronized(new Hashtable());
            processes   = ArrayList.Synchronized(new ArrayList());

            pending_events = Hashtable.Synchronized(new Hashtable());

            last_pending_sigstop = DateTime.Now;
            pending_sigstops     = new Dictionary <int, DateTime> ();

            address_domain = AddressDomain.Global;

            wait_event   = new ST.AutoResetEvent(false);
            engine_event = new ST.ManualResetEvent(true);
            ready_event  = new ST.ManualResetEvent(false);

            event_queue            = new DebuggerEventQueue("event_queue");
            event_queue.DebugFlags = DebugFlags.Wait;

            mono_debugger_server_global_init();

            wait_thread = new ST.Thread(new ST.ThreadStart(start_wait_thread));
            wait_thread.IsBackground = true;
            wait_thread.Start();

            inferior_thread = new ST.Thread(new ST.ThreadStart(start_inferior));
            inferior_thread.IsBackground = true;
            inferior_thread.Start();

            ready_event.WaitOne();
        }
Beispiel #37
0
        private bool RawSendHelper(byte[] aData, bool aWait)
        {
            if (IsInBackgroundThread)
            {
                return SendRawData(aData);
            }
            if (!IsConnected)
            {
                return false;
            }
            if (aWait)
            {
                using (var xEvent = new AutoResetEvent(false))
                {
                    mPendingWrites.Add(new Outgoing {Packet = aData, Completed = xEvent});
                    while (IsConnected)
                    {
                        xEvent.WaitOne(1000);
                    }
                    return IsConnected; // ??
                }
            }
            else
            {
                mPendingWrites.Add(new Outgoing {Packet = aData});
                return true;
            }

        }
Beispiel #38
0
 public object SendEvent(int events, object param)
 {
     if (threadid == MT.Thread.CurrentThread.ManagedThreadId)
     {
         bool success = true;
         while (success)
         {
             DoEvent(ref success);
         }
         return(OnProc(events, param));
     }
     else
     {
         using (MT.AutoResetEvent signal = new MT.AutoResetEvent(false))
         {
             object result = null;
             PostEvent(events, param, (response) =>
             {
                 result = response;
                 signal.Set();
             });
             while (!signal.WaitOne(1))
             {
                 ;
             }
             return(result);
         }
     }
 }
Beispiel #39
0
 public DDEClient()
 {
     AutoResetEvent are = new AutoResetEvent(false);
     thread = new Thread(this.ThreadMain);
     thread.Start(are);
     are.WaitOne();
 }
Beispiel #40
0
        async public static Task <System.Drawing.Rectangle> GetitAsync()
        {
            if (VersionHelper.IsWindows8OrGreater())
            {
                _overlayWindow = new Interfaces.Overlay.OverlayWindow(true);
            }
            else
            {
                _overlayWindow = new Interfaces.Overlay.OverlayWindow(false);
            }
            _overlayWindow.Visible = true;
            _overlayWindow.Bounds  = new System.Drawing.Rectangle(0, 0, 10, 10);
            createform();

            mouseDown = false;
            var pos = System.Windows.Forms.Cursor.Position;

            rect = new System.Drawing.Rectangle(pos.X, pos.Y, 1, 1);
            //hi = new Highlighter(rect, System.Drawing.Color.Red);

            OpenRPA.Input.InputDriver.Instance.OnMouseDown += onMouseDown;
            OpenRPA.Input.InputDriver.Instance.OnMouseUp   += onMouseUp;
            OpenRPA.Input.InputDriver.Instance.OnMouseMove += onMouseMove;
            OpenRPA.Input.InputDriver.Instance.onCancel    += onCancel;
            OpenRPA.Input.InputDriver.Instance.CallNext     = false;

            waitHandle = new System.Threading.AutoResetEvent(false);
            await waitHandle.WaitOneAsync();

            //System.Windows.Forms.Application.Exit();

            return(rect);
        }
        public void Should_be_able_to_do_basic_request_async_cancellation()
        {
            const string expectedResult = "Sending back 'Ninja!!'";
            var autoResetEvent = new AutoResetEvent(false);

            bus.Respond<TestRequestMessage, TestResponseMessage>(request =>
            {
                var response = new TestResponseMessage
                {
                    Text = string.Format("Sending back '{0}'", request.Text)
                };
                return response;
            });

            using (var channel = bus.OpenPublishChannel())
            {
                var request = new TestRequestMessage { Text = "Ninja!!" };

                var cancellationSource = new CancellationTokenSource();

                var responseTask = channel.RequestAsync<TestRequestMessage, TestResponseMessage>(request, cancellationSource.Token);

                responseTask.ContinueWith(t =>
                {
                    autoResetEvent.Set();
                }, TaskContinuationOptions.OnlyOnCanceled);

                cancellationSource.Cancel();
            }

            // give the bus a chance to deliver the message
            Assert.IsTrue(autoResetEvent.WaitOne(1000));
        }
Beispiel #42
0
        public static bool ClearMarkedPosts(ThreadMetadata thread, int timeout = CoreConstants.DEFAULT_TIMEOUT_IN_MILLISECONDS)
        {
            // create request
            HttpWebRequest request = AwfulWebRequest.CreateFormDataPostRequest(
                "http://forums.somethingawful.com/showthread.php",
                "application/x-www-form-urlencoded");

            // begin request stream creation and wait...
            var signal = new AutoResetEvent(false);
            var result = request.BeginGetRequestStream(callback =>
                SendClearMarkedPostRequest(callback, signal, thread),
                request);

            signal.WaitOne();

            // begin response stream and wait...
            request = result.AsyncState as HttpWebRequest;
            result = request.BeginGetResponse(callback => { signal.Set(); }, request);
            signal.WaitOne(timeout);

            if (!result.IsCompleted)
                throw new TimeoutException();

            // process the response and return status
            bool success = ProcessClearMarkedPostResponse(result);
            return success;
        }
        public void AsyncStorageModule_InvalidKeyValue_Method()
        {
            var module = new AsyncStorageModule();
            var waitHandle = new AutoResetEvent(false);

            var error = default(JObject);
            var result = default(JArray);
            var callback = new MockCallback(res =>
            {
                error = res.Length > 0 ? (JObject)res[0] : null;
                result = res.Length > 1 ? (JArray)res[1] : null;
                waitHandle.Set();
            });

            var array = new[]
            {
                new[] { "5", "5", "5" },
            };

            module.clear(callback);
            Assert.IsTrue(waitHandle.WaitOne());
            Assert.IsNull(error);
            Assert.IsNull(result);

            module.multiSet(array, callback);
            Assert.IsTrue(waitHandle.WaitOne());
            Assert.AreEqual(error["message"], "Invalid Value");
            Assert.IsNull(result);
        }
        public void Should_invoke_onReceiveMessage_delegate_with_copied_MessageDeliverEventArgs()
        {
            // Arrange
            MessageDeliverEventArgs eventArgs = null;
            var are = new AutoResetEvent(false);
            
            var func = consumer.CreateJobFactoryForTest<Customer>("subscriptionName", (c, e) => { eventArgs = e; are.Set(); });
            var basicProperties = Substitute.For<IBasicProperties>();
            basicProperties.Type.Returns(Global.DefaultTypeNameSerializer.Serialize(typeof(Customer)));

            // Action
            func(new BasicDeliverEventArgs
            {
                BasicProperties = basicProperties,
                ConsumerTag = "ct",
                DeliveryTag = 1000,
            });

            // Assert
            are.WaitOne();
            Assert.AreEqual("ct", eventArgs.ConsumerTag);
            Assert.AreEqual((ulong)1000, eventArgs.DeliveryTag);
            Assert.AreEqual("subscriptionName", eventArgs.SubscriptionName);

        }
Beispiel #45
0
        private static void DemoOne()
        {
            //AutoResetEvent example
            //AutoResetEvent 通知正在等待的线程已发生的事件。
            AutoResetEvent waitHandler = new AutoResetEvent(false);//false 即非终止,未触发。

            new Thread(() =>
            {
                waitHandler.WaitOne();  //阻塞当前线程,等待底层内核对象收到信号。
                Console.WriteLine("线程1接收到信号,开始处理。");

            }).Start();

            new Thread(() =>
            {
                waitHandler.WaitOne();  //阻塞当前线程,等待底层内核对象收到信号。
                Console.WriteLine("线程2接收到信号,开始处理。");

            }).Start();

            new Thread(() =>
            {
                Thread.Sleep(2000);
                Console.WriteLine("线程3发信号");
                waitHandler.Set();    //向内核对象发送信号。设置事件对象为非终止状态、false,解除阻塞。  

            }).Start();

            //waitHandler.Close(); //释放句柄资源。
            //waitHandler.Reset();  //手动设置事件为非终止状态、false,线程阻止。
            Console.ReadLine();
        }
        /// <summary>
        /// Constructor
        /// </summary>
        public Console()
        {
            InitializeComponent();
            textpen        = new Pen(Settings.Simulator.ConsoleTextColor);      //color of the init text
            this.BackColor = Settings.Simulator.ConsoleBackGroundColor;

            caretThread = new Thread(new ThreadStart(ShowCaret));
            AllThreads.Add(caretThread);              //add the caret thread to list for closing
            caretThread.Start();

            m_Output = new dOutputFunction(this.Write);
            m_Exit   = new dExitFunction(this.exitConsole);

            ScreenBuffer = new ArrayList();
            InputBuffer  = new CodeBlock();
            ScreenBuffer.Insert(0, new CodeBlock());

            bNowInInputFunction = false;

            eWaitForInput = new AutoResetEvent(false);

            PrevImage = new System.Drawing.Bitmap(_MaxX, _MaxY);

            NeedToRepaint          = new System.Timers.Timer();
            NeedToRepaint.Elapsed += new ElapsedEventHandler(ConsoleUpdateTime);
            NeedToRepaint.Interval = 100;
            NeedToRepaint.Enabled  = false;
        }
Beispiel #47
0
 /* The implementation of Storage is hidden from users, although it is protected
  * so you can derive from it if you want to. If you do, you have to write a new
  * Attach() function as well, as that function attaches an instance of this
  * specific class.
  */
 protected Storage()
     : base(GameInstance)
 {
     todo   = new System.Threading.AutoResetEvent(false);
     thread = new System.Threading.Thread(this.Worker);
     thread.Start();
     GameInstance.Components.Add(this);
 }
Beispiel #48
0
 public Camera(string camName)
 {
     this._camName    = camName;
     this._ThreadFlag = true;
     this._ent        = new AutoResetEvent(false);
     TaskFactory factory = new TaskFactory();
     Task        a       = factory.StartNew(snapImage);
 }
Beispiel #49
0
 public RunWorkflowInstance(string UniqueId, string IDOrRelativeFilename, bool WaitForCompleted, Dictionary <string, object> Arguments)
 {
     this.UniqueId             = UniqueId;
     this.IDOrRelativeFilename = IDOrRelativeFilename;
     this.WaitForCompleted     = WaitForCompleted;
     this.Arguments            = Arguments;
     Started = false;
     Pending = new System.Threading.AutoResetEvent(false);
 }
Beispiel #50
0
        public AutoResetEventExpire(bool initialState, int expireTime)
        {
            are = new System.Threading.AutoResetEvent(initialState);

            setTimer           = new System.Timers.Timer();
            setTimer.Interval  = expireTime;
            setTimer.Elapsed  += OnTimedEvent;
            setTimer.AutoReset = false;
            setTimer.Enabled   = true;
        }
Beispiel #51
0
 private void Initialize()
 {
     index         = 1;
     packetSize    = 32768;
     buffer        = new byte[MaxPduSize];
     State         = State.Closed;
     completeEvent = new System.Threading.AutoResetEvent(false);
     threadEvent   = new AutoResetEvent(false);
     services      = new List <ServiceClass>();
 }
Beispiel #52
0
        public ASyncRead(SerialPort com)
        {
            _com    = com;
            _result = int.MinValue;

            _readCompletedEvent = new System.Threading.AutoResetEvent(false);
            _readStartedEvent   = new System.Threading.AutoResetEvent(false);

            _exception = null;
        }
        private Timer InitalizeAlgorthmTimer(CancelationObject cancelationSignal, AutoResetEvent autoResetEvent)
        {
            Timer timer = new Timer();

            timer.Elapsed  += (sender, e) => AlgorthmTimerElapsedCallback(sender, e, cancelationSignal, autoResetEvent);
            timer.Interval  = 10000;
            timer.AutoReset = false;

            return(timer);
        }
Beispiel #54
0
 static internal void ClearAutoEvents()
 {
     lock (_sLockObj)
     {
         while (_AutoEventQueue.Count > 0)
         {
             System.Threading.AutoResetEvent aEvent = _AutoEventQueue.Dequeue();
             aEvent.Set();
         }
     }
 }
 void OnEnable()
 {
     jobEvent        = new System.Threading.AutoResetEvent(false);
     exit            = false;
     deep            = false;
     thread          = new System.Threading.Thread(threadMain);
     thread.Priority = System.Threading.ThreadPriority.AboveNormal;
     thread.Start();
     coGarbageCollection = garbageCollection();
     StartCoroutine(coGarbageCollection);
 }
Beispiel #56
0
        public CustomQueue(string name, CancellationToken token)
        {
            AllServed      = 0;
            AverageLentgth = 0;
            Name           = name;
            _reachedLimit  = false;
            HasLimit       = false;
            customersList  = new Queue <Customer>();
            resetEvent     = new System.Threading.AutoResetEvent(false);

            new Thread(() => UpdateAvrLength(token)).Start();
        }
Beispiel #57
0
 /// <summary>
 /// Starts the invokable thread with a specified priority. The <paramref name="name"/> argument is used for debugging purposes, it is assigned to the thread.
 /// </summary>
 /// <param name="name">The name of the thread (as it then appears in TaskManager).</param>
 /// <param name="priority">The priority of the thread.</param>
 protected void Start(string name, System.Threading.ThreadPriority priority)
 {
     _keepThreadRunning = true;
     _triggeringEvent   = new AutoResetEvent(false);
     _thread            = new Thread(EhThreadBody)
     {
         IsBackground = true,
         Priority     = priority,
         Name         = name
     };
     _thread.Start();
 }
Beispiel #58
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.ByteStream.Close();
                this.sendRateLimit.Dispose();
                this.internalCancellation.Dispose();
            }

            System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false);
            are.WaitOne(100);
        }
Beispiel #59
0
        internal CommandLineInterpreter(DebuggerOptions options, bool is_interactive)
        {
            if (options.HasDebugFlags)
            {
                Report.Initialize(options.DebugOutput, options.DebugFlags);
            }
            else
            {
                Report.Initialize();
            }

            Configuration = new DebuggerConfiguration();
#if HAVE_XSP
            if (options.StartXSP)
            {
                Configuration.SetupXSP();
            }
            else
            {
                Configuration.LoadConfiguration();
            }
#else
            Configuration.LoadConfiguration();
#endif

            Configuration.SetupCLI();

            interpreter     = new Interpreter(is_interactive, Configuration, options);
            interpreter.CLI = this;

            engine = interpreter.DebuggerEngine;
            parser = new LineParser(engine);

            if (!interpreter.IsScript)
            {
                line_editor = new LineEditor("mdb");

                line_editor.AutoCompleteEvent += delegate(string text, int pos) {
                    return(engine.Completer.Complete(text, pos));
                };

                Console.CancelKeyPress += control_c_event;
            }

            interrupt_event          = new ST.AutoResetEvent(false);
            nested_break_state_event = new ST.AutoResetEvent(false);

            main_loop_stack = new Stack <MainLoop> ();
            main_loop_stack.Push(new MainLoop(interpreter));

            main_thread = new ST.Thread(new ST.ThreadStart(main_thread_main));
            main_thread.IsBackground = true;
        }
Beispiel #60
0
 /// <summary>
 /// Creates new program. Get CodeBlock to load into the simulator's memory
 /// </summary>
 /// <param name="cbProgram">CodeBlock to load into the simulator's memory</param>
 /// <param name="DebugMode">True if the new program suppose to run in debug mode</param>
 public Program(ProgramBlock cbProgram, bool DebugMode, frmMain theMainApplication, string sInputFile, string sOutputFile)
 {
     theProgram          = cbProgram;
     _theMainApplication = theMainApplication;
     BreakPointWait      = new AutoResetEvent(false);
     _BreakPointList     = new BreakPointList();
     bInDebug            = DebugMode;
     con          = new VAX11Simulator.Console(sInputFile, sOutputFile);
     theSimulator = new VAX11Simulator.Simulator(theProgram, con);
     theSimulator.memory.OnMemoryAccess += new MemoryAccessedFunc(MemoryAcessedHandler);
     theSimulator.memory.OnPageFault    += new PageFaultFunc(PageFaultHandler);
     con.InterruptsEvent += new VAX11Simulator.Console.InterruptsDelegate(InterruptHendler);
 }