public void RequestGeneratorRetrieveTest()
        {
            IRequestGenerator requestGenerator = new WebRequestGenerator();
            const string TestUri = "http://beta-api.etsy.com/v1/listings/featured/front?offset=0&limit=10&detail_level=low&api_key=" +
                NetsyData.EtsyApiKey;

            string resultString = string.Empty;
            Exception ex = null;

            using (AutoResetEvent waitEvent = new AutoResetEvent(false))
            {
                Action<string> successAction = s =>
                     {
                        resultString = s;
                        waitEvent.Set();
                     };

                Action<Exception> errorAction = e =>
                    {
                        ex = e;
                        waitEvent.Set();
                    };

                requestGenerator.StartRequest(new Uri(TestUri), successAction, errorAction);
                bool signalled = waitEvent.WaitOne(Constants.WaitTimeout);

                Assert.IsTrue(signalled);
                Assert.IsFalse(string.IsNullOrEmpty(resultString));
                Assert.IsNull(ex);
            }
        }
예제 #2
0
 public void TestDelete()
 {
     FileInfo file = new FileInfo(@"d:\X16-42552VS2010UltimTrial1.txt");
     AutoResetEvent are = new AutoResetEvent(false);
     string key = null;
     HttpCommunicate.Upload(file, (result, warning) =>
     {
         Console.WriteLine("result:" + result);
         key = result + "";
         are.Set();
     }, error =>
     {
         Console.WriteLine("error:" + error);
         are.Set();
     });
     are.WaitOne();
     are.Reset();
     FileDeletePackage package = new FileDeletePackage();
     package.key = key;
     HttpCommunicate.Request(package, (result, warning) =>
     {
         Console.WriteLine("file:" + result);
         are.Set();
     }, error =>
     {
         Console.WriteLine("error:" + error);
         are.Set();
     });
     are.WaitOne();
 }
예제 #3
0
        static void Main(string[] args)
        {
            using (WorkflowRuntime workflowRuntime = new WorkflowRuntime())
            {
                // Add ChannelManager
                ChannelManagerService channelmgr = new ChannelManagerService();
                workflowRuntime.AddService(channelmgr);
                
                AutoResetEvent waitHandle = new AutoResetEvent(false);
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) { Console.WriteLine("WorkflowCompleted: " + e.WorkflowInstance.InstanceId.ToString()); waitHandle.Set(); };
                workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e) { Console.WriteLine("WorkflowTerminated: " + e.Exception.Message); waitHandle.Set(); };

                while (true)
                {
                    WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(Microsoft.WorkflowServices.Samples.SequentialCalculatorClient));
                    Console.WriteLine("Start SequentialCalculatorClient.");
                    instance.Start();
                    waitHandle.WaitOne();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Do another calculation? (Y)");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Press <enter> to exit.");
                    Console.ResetColor();
                    string input = Console.ReadLine();
                    if (input.Length == 0 || input[0] != 'Y')
                        break;
                    waitHandle.Reset();
                }
            }
        }
예제 #4
0
파일: Do_Tests.cs 프로젝트: blesh/ALE
        public void Do_Timeout()
        {
            var sw = Stopwatch.StartNew();
            const int ms = 100;
            var i = 0;
            var ellapsed = 0L;
            var wait = new AutoResetEvent(false);
            Do.Timeout(() =>
                           {
                               ellapsed = sw.ElapsedMilliseconds;
                               i++;
                               wait.Set();
                           }, ms);
            if (wait.WaitOne(ms * 3))
            {
                Assert.AreEqual(1, i);
                Assert.IsTrue(ellapsed > ms * .9);
            } else
            {
                Assert.Fail("callback not executed.");
            }

            sw.Restart();
            var killswitch = Do.Timeout(() => { wait.Set(); }, ms * 2);
            killswitch.Kill();
            ellapsed = sw.ElapsedMilliseconds;
            Assert.IsTrue(ellapsed < ms * 2);
            if (wait.WaitOne(ms * 4))
            {
                Assert.Fail("Unable to stop timeout.");
            }
        }
예제 #5
0
        static void Main(string[] args)
        {
            using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())
            {
                AutoResetEvent waitHandle = new AutoResetEvent(false);
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) 
                {
                    Console.WriteLine("Workflow completed.");
                    waitHandle.Set();
                };
                workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
                {
                    Console.WriteLine(e.Exception.Message);
                    waitHandle.Set();
                };

                WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(StateInitialization.SampleWorkflow));
                Console.WriteLine("Starting workflow.");
                instance.Start();

                waitHandle.WaitOne();

                workflowRuntime.StopRuntime();
            }
        }
        public void Test_SendToWrongPort()
        {
            IPEndPoint ep1 = new IPEndPoint (IPAddress.Parse ("10.0.0.1"), 10000);
            IPEndPoint ep2 = new IPEndPoint (IPAddress.Parse ("10.0.0.2"), 10000);

            VirtualNetwork network = new VirtualNetwork (LatencyTypes.Constant (20), 5, PacketLossType.Lossless (), 2);
            byte[] msg = new byte[]{0, 1, 2, 3};
            try {
                using (AutoResetEvent done = new AutoResetEvent (false))
                using (VirtualDatagramEventSocket sock1 = new VirtualDatagramEventSocket (network, ep1.Address))
                using (VirtualDatagramEventSocket sock2 = new VirtualDatagramEventSocket (network, ep2.Address)) {
                    sock1.Bind (new IPEndPoint (IPAddress.Any, ep1.Port));
                    sock2.Bind (new IPEndPoint (IPAddress.Any, ep2.Port));
                    sock1.Received += new DatagramReceiveEventHandler (delegate (object sender, DatagramReceiveEventArgs e) {
                        done.Set ();
                    });
                    sock2.Received += new DatagramReceiveEventHandler (delegate (object sender, DatagramReceiveEventArgs e) {
                        done.Set ();
                    });
                    sock1.SendTo (msg, new IPEndPoint (ep2.Address, ep2.Port + 1));
                    Assert.IsFalse (done.WaitOne (500));
                    sock2.SendTo (msg, ep1);
                    Assert.IsTrue (done.WaitOne ());
                }
            } finally {
                network.Close ();
            }
        }
예제 #7
0
        public static ITileSource Build(
            string urlToTileMapXml, 
            bool overrideTmsUrlWithUrlToTileMapXml)
        {
            var webRequest = (HttpWebRequest) WebRequest.Create(urlToTileMapXml);
            var waitHandle = new AutoResetEvent(false);
            ITileSource tileSource = null;
            Exception error = null;

            var state = new object[]
            {
                new Action<Exception>(ex =>
                {
                    error = ex;
                    waitHandle.Set();
                }),
                new Action<ITileSource>(ts =>
                {
                    tileSource = ts;
                    waitHandle.Set();
                }),
                webRequest,
                urlToTileMapXml,
                overrideTmsUrlWithUrlToTileMapXml
            };
            webRequest.BeginGetResponse(LoadTmsLayer, state);

            waitHandle.WaitOne();
            if (error != null) throw error;
            return tileSource;
        }
예제 #8
0
        static int Main(string[] args)
        {
            var finishedProcessing = new AutoResetEvent(false);
            int returnCode = 0;

            var index = new IndexFiles();
            index.Out_Statistics += stats =>
                {
                    System.Console.WriteLine("Successfully indexed {0} words.", stats.WordCount);
                    returnCode = 0;
                    finishedProcessing.Set();
                };

            index.Out_ValidationError += err =>
                {
                    System.Console.WriteLine("*** Aborted indexing! Validation error: {0}", err);
                    returnCode = 1;
                    finishedProcessing.Set();
                };

            index.Out_UnhandledException += ex =>
                {
                    System.Console.WriteLine("*** Aborted indexing! Unexpected exception: {0}. See log for details.", ex.Message);
                    returnCode = 99;
                    finishedProcessing.Set();
                };

            System.Console.WriteLine("Indexing files in {0} [Thread {1}]", args[0], Thread.CurrentThread.GetHashCode());

            index.Index(args[0], args[1]);

            finishedProcessing.WaitOne();
            return returnCode;
        }
예제 #9
0
 public static void Stop()
 {
     bRun = false;
     for (int i = 0; i < ThreadHandle.Length; i++)
     {
         AEvent.Set();
         Thread.Sleep(10);
     }
     for (int i = 0; i < ThreadHandle.Length; i++)
     {
         try
         {
             if (ThreadHandle[i].ThreadState != ThreadState.Stopped)
             {
                 ThreadHandle[i].Abort();
             }
         }
         catch
         {
         }
     }
     if (AEvent != null)
     {
         AEvent.Close();
     }
 }
예제 #10
0
            public void should_consume_with_valid_consumer()
            {
                int result = 0;
                var waitHandle = new AutoResetEvent(false);

                IBus producer = this.StartBus(
                    "producer",
                    cfg =>
                        {
                            Func<IRouteResolverBuilder, IRouteResolver> routeResolverBuilder = b => b.Topology.Declare(Exchange.Named("multi.exchange"));

                            cfg.Route("boo.request")
                                .ConfiguredWith(routeResolverBuilder);
                            cfg.Route("foo.request")
                                .ConfiguredWith(routeResolverBuilder);
                        });

                this.StartBus(
                    "consumer",
                    cfg =>
                        {
                            Func<ISubscriptionEndpointBuilder, ISubscriptionEndpoint> subscriptionBuilder = b =>
                                {
                                    Exchange e = b.Topology.Declare(Exchange.Named("multi.exchange"));
                                    Queue q = b.Topology.Declare(Queue.Named("multi.queue"));
                                    b.Topology.Bind(e, q);

                                    return new SubscriptionEndpoint(q, e);
                                };

                            cfg.On<BooMessage>("boo.request")
                                .ReactWith(
                                    (m, ctx) =>
                                        {
                                            result = m.Num;
                                            waitHandle.Set();
                                        })
                                .WithEndpoint(subscriptionBuilder);
                            cfg.On<FooMessage>("foo.request")
                                .ReactWith(
                                    (m, ctx) =>
                                        {
                                            result = m.Num * 2;
                                            waitHandle.Set();
                                        })
                                .WithEndpoint(subscriptionBuilder);
                        });

                producer.Emit("boo.request", new BooMessage(13));

                waitHandle.WaitOne(5.Seconds()).Should().BeTrue();

                result.Should().Be(13);

                producer.Emit("foo.request", new FooMessage(13));

                waitHandle.WaitOne(5.Seconds()).Should().BeTrue();

                result.Should().Be(26);
            }
        public void TestDisconnect()
        {
            var ev = new AutoResetEvent(false);
            var succeeded = false;
            var communicationLayer = new SocketConnection();
            communicationLayer.ConnectionSucceeded += () =>
            {
                succeeded = true;
                ev.Set();
            };
            communicationLayer.ErrorOccurred += (msg) =>
            {
                succeeded = false;
                ev.Set();
            };
            communicationLayer.StartConnect("localhost", 80);
            ev.WaitOne(5000);
            Assert.IsTrue(succeeded);

            var disconnectEv = new AutoResetEvent(false);
            communicationLayer.ServerDisconnected += () => disconnectEv.Set();
            communicationLayer.StartDisconnect();

            disconnectEv.WaitOne(5000);
            Assert.IsFalse(communicationLayer.Connected);
        }
		public async Task Test_QueueUrl_AlreadyQueued1 ()
		{
			var bus = new InProcessBus ();
			var repo = new DownloadRepositoryMock ();
			var manager = new DownloadManager.iOS.DownloadManager (bus, repo);
			var wait1 = new AutoResetEvent (false);

			bool alreadyQueued = false;
			bool checkFreeSlot = false;

			bus.Subscribe<AlreadyQueued> (p => {
				alreadyQueued = true;
				wait1.Set();
			});

			bus.Subscribe<CheckFreeSlot> (p => {
				checkFreeSlot = true;
				wait1.Set();
			});

			repo.Insert(new Download {
				Url = "http://url.com/download/file.zip"
			});

			manager.QueueUrl (new QueueUrl {
				Url = "http://url.com/download/file.zip"
			});

			wait1.WaitOne ();

			Assert.AreEqual (false, checkFreeSlot);
			Assert.AreEqual (true, alreadyQueued);

		}
        public void Intercept(IInvocation invocation)
        {
            var circuitName = invocation.Method.DeclaringType.Name;

            // Setup a new circuit if needed
            if (!_circuits.ContainsKey(circuitName))
            {
                _circuits.Add(circuitName, new Circuit());
            }

            var circuit = _circuits[circuitName];

            // If the circuit breaker has been tripped, fail fast 
            if (circuit.IsOffline)
            {
                throw new Exception("This service is misbehaving and has been taken offline");
            }

            // The circuit breaker hasn't been tripped - allow it
            try
            {
                var autoReset = new AutoResetEvent(false);
                var exception = null as Exception;
                ThreadPool.QueueUserWorkItem(
                    thread =>
                        {
                            try
                            {

                                invocation.Proceed();
                                autoReset.Set();
                            }
                            catch (Exception innerException)
                            {
                                exception = innerException;
                                autoReset.Set();
                            }
                        });
                var success = autoReset.WaitOne(3000);
                if (!success)
                {
                    // It timed out
                    circuit.RecordTimeout();
                    throw new TimeoutException("The call timed out");
                }
                if (exception != null)
                {
                    throw exception;
                }
            }
            catch (TimeoutException) 
            {
                throw;
            }
            catch (Exception ex)
            {
                circuit.RecordException(ex);
                throw;
            }
        }
        /// <summary>
        /// Create a Pusher Client, and subscribes a user
        /// </summary>
        /// <param name="pusherServer">Server to connect to</param>
        /// <param name="reset">The AutoReset to control the subscription by the client</param>
        /// <param name="channelName">The name of the channel to subscribe to</param>
        /// <returns>A subscribed client</returns>
        public static PusherClient.Pusher CreateClient(Pusher pusherServer, AutoResetEvent reset, string channelName)
        {
            PusherClient.Pusher pusherClient =
                new PusherClient.Pusher(Config.AppKey, new PusherClient.PusherOptions()
                {
                    Authorizer = new InMemoryAuthorizer(
                        pusherServer,
                        new PresenceChannelData()
                        {
                            user_id = "Mr Pusher",
                            user_info = new { twitter_id = "@pusher" }
                        })
                });

            pusherClient.Connected += delegate { reset.Set(); };

            pusherClient.Connect();

            reset.WaitOne(TimeSpan.FromSeconds(5));

            var channel = pusherClient.Subscribe(channelName);

            channel.Subscribed += delegate { reset.Set(); };

            reset.WaitOne(TimeSpan.FromSeconds(5));

            return pusherClient;
        }
예제 #15
0
 private void Channel_HostInfoUpdated(object sender, EventArgs e)
 {
     SyncContext.Post(dummy => {
         hostInfoUpdated = true;
         changedEvent.Set();
     }, null);
 }
예제 #16
0
        public static void SearchingWithCancellation()
        {
            Demo.DisplayHeader("Creating async observable with async-await and cancellation");

            var exampleResetEvent = new AutoResetEvent(false);

            // Change the index to when you want the subscription disposed
            int cancelIndex = 1;

            var results = SearchEngineExample.Search_WithCancellation("Rx");

            IDisposable subscription = Disposable.Empty;
            subscription = results
                .Select((result, index) => new { result, index }) //adding the item index to the notification
                .Do(x =>
                {
                    if (x.index == cancelIndex)
                    {
                        Console.WriteLine("Cancelling on index {0}", cancelIndex);
                        subscription.Dispose();
                        exampleResetEvent.Set();
                    }
                })
                .Select(x => x.result) //rollback the observable to be IObservable<string>
                 .DoLast(() => exampleResetEvent.Set(), delay: TimeSpan.FromSeconds(1))
                .SubscribeConsole("results");

            exampleResetEvent.WaitOne();
        }
예제 #17
0
        static void Main(string[] args)
        {
            m_WebSockets = new WebSocket[1000];

            var autoEventReset = new AutoResetEvent(false);

            for(var i = 0; i < m_WebSockets.Length; i++)
            {
                var websocket = new WebSocket("ws://localhost:2011/");
                websocket.Opened += (s, e) =>
                    {
                        autoEventReset.Set();
                    };
                websocket.Error +=  (s, e) =>
                    {
                        Console.WriteLine(e.Exception.Message);
                        autoEventReset.Set();
                    };

                websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived);
                websocket.Open();
                autoEventReset.WaitOne();

                m_WebSockets[i] = websocket;

                Console.WriteLine(i);
            }

            Console.WriteLine("All connected");
            Console.ReadLine();
        }
예제 #18
0
        public void DispatchActionToMainWindow(Action message)
        {
            bool loaded = false;

            if (Application.Current.Dispatcher.HasShutdownStarted)
                message();

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if (Application.Current.MainWindow != null)
                {
                    loaded = Application.Current.MainWindow.IsLoaded;
                    return;
                }
                loaded = false;
            }));
            if (!loaded)
            {
                var handle = new AutoResetEvent(false);
                EventHandler set = delegate { handle.Set(); };
                Application.Current.Dispatcher.Invoke(
                    new Action(() =>
                    {
                        if (Application.Current.MainWindow != null)
                            Application.Current.MainWindow.Loaded += (sender, args) => handle.Set();
                        else
                            Application.Current.Activated += set;
                    }));

                handle.WaitOne();
                Application.Current.Activated -= set;
            }

            Application.Current.Dispatcher.Invoke(message);
        }
예제 #19
0
        public void CurrentIsVisibleAccrossThreads()
        {
            var sqlCharacters = new TestSqlCharacters();

            SqlCharacters actual = null;
            var handle = new AutoResetEvent(false);

            var thread1 = new Thread(() =>
            {
                SqlCharacters.Current = sqlCharacters;
                handle.Set();
            });

            var thread2 = new Thread(() =>
            {
                actual = SqlCharacters.Current;
                handle.Set();
            });

            thread1.Start();
            handle.WaitOne();

            thread2.Start();
            handle.WaitOne();

            thread1.Abort();
            thread2.Abort();

            Assert.Same(sqlCharacters, actual);
        }
예제 #20
0
        public void when_receiving_message_then_can_send_new_message()
        {
            var secondReceiver = new TestableMessageReceiver(this.connectionFactory);

            this.sender.Send(new Message("message1"));

            var waitEvent = new AutoResetEvent(false);
            string receiver1Message = null;
            string receiver2Message = null;

            this.receiver.MessageReceived += (s, e) =>
            {
                waitEvent.Set();
                receiver1Message = e.Message.Body;
                waitEvent.WaitOne();
            };
            secondReceiver.MessageReceived += (s, e) =>
            {
                receiver2Message = e.Message.Body;
            };

            ThreadPool.QueueUserWorkItem(_ => { this.receiver.ReceiveMessage(); });

            Assert.IsTrue(waitEvent.WaitOne(TimeSpan.FromSeconds(10)));
            this.sender.Send(new Message("message2"));
            secondReceiver.ReceiveMessage();
            waitEvent.Set();

            Assert.IsTrue("message1" == receiver1Message);
            Assert.IsTrue("message2" == receiver2Message);
        }
예제 #21
0
파일: StaticTests.cs 프로젝트: lebaon/AEF
        public void MessageAfterExceptionTest()
        {
            Exception e = null;
            AutoResetEvent even = new AutoResetEvent(false);
            int y = 0;
            var a = new Arbitr<Message, NOPMessage>(
                (z) =>
                {
                    y = 1 / z.x;
                    even.Set();
                },
                (z) =>
                {
                    e = z;
                    even.Set();
                });

            a.Send(new Message() { x = 0 });
            bool completed = even.WaitOne(500);

            Assert.IsTrue(completed);
            Assert.IsNotNull(e);
            Assert.AreEqual(y, 0);

            e = null;
            a.Send(new Message() { x = 1 });
            completed = even.WaitOne(500);

            Assert.IsTrue(completed);
            Assert.IsNull(e);
            Assert.AreEqual(y, 1);
        }
예제 #22
0
파일: Channel.cs 프로젝트: notflan/Sync
        /// <summary>
        /// Send an object to the channel. Blocks until there is room to send or the channel is closed.
        /// </summary>
        public void Send(T t)
        {
start:
            if (closing)
            {
                return;
            }
            lock (qlock)
            {
                int c = queue.Count;

                if (backlog > 0 && c >= backlog)
                {
                    goto wait;
                }

                if (closing)
                {
                    return;
                }
                queue.Enqueue(t);
                reset.Set();
                return;
            }
wait:
            if (ShiftOnFull)
            {
                Receive();
            }
            resetR.WaitOne();
            goto start;
        }
예제 #23
0
        static void Main(string[] args)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);

            // create the workflow app and add handlers for the Idle and Completed actions
            WorkflowApplication app = new WorkflowApplication(new Sequence1());
            app.Idle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                syncEvent.Set();
            };
            app.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                syncEvent.Set();
            };

            // start the application
            app.Run();
            syncEvent.WaitOne();

            // read some text from the console and resume the readText bookmark (created in the first WaitForInput activity)
            string text = Console.ReadLine();
            app.ResumeBookmark("readText", text);
            syncEvent.WaitOne();

            // read some text from the console, convert it to number, and resume the readNumber bookmark (created in the second WaitForInput activity)
            int number = ReadNumberFromConsole();
            app.ResumeBookmark("readNumber", number);
            syncEvent.WaitOne();

            Console.WriteLine("");
            Console.WriteLine("Press [ENTER] to exit...");
            Console.ReadLine();
        }
예제 #24
0
        /// <summary>
        /// Считает время ожидания ответа на запрос к http серверу
        /// </summary>
        /// <param name="address">Url адрес</param>
        /// <param name="maxRequestTime">Максимальное время ожидания ответа. -1 для бесконечного времени ожидания.</param>
        /// <returns>Время запроса в мс</returns>

        internal static int GetRequestTime(string address, RequestParams requestParams, int maxRequestTime, out Exception outEx)
        {
            int result = -1;
            Exception innerEx = null;
            using (var request = new HttpRequest())
            {
                request.UserAgent = HttpHelper.ChromeUserAgent();
                EventWaitHandle wh = new AutoResetEvent(false);
                var requestThread = new Thread(() =>
                {
                    var watch = new Stopwatch();
                    watch.Start();
                    try
                    {
                        string resultPage = request.Get(address, requestParams).ToString();
                    }
                    catch (Exception ex) { innerEx = ex; }
                    result = Convert.ToInt32(watch.ElapsedMilliseconds);
                    watch.Reset();
                    wh.Set();
                });
                requestThread.Start();
                var stoptimer = new System.Threading.Timer((Object state) =>
                {
                    requestThread.Abort();
                    wh.Set();
                }, null, maxRequestTime, Timeout.Infinite);
                wh.WaitOne();

                stoptimer.Dispose();
            }
            outEx = innerEx;
            return result;
        }
        public void Test_Add_and_Retrieve()
        {
            var testBooking = CreateTestBooking();

            Booking actual = null;
            var waiter = new AutoResetEvent(false);
            _client.AddBookingAsync(testBooking, booking =>
                {
                    actual = booking;
                    waiter.Set();
                });

            Assert.IsTrue(waiter.WaitOne(1000), "Timeout waiting for WCF asynk result");
            Assert.AreNotSame(testBooking, actual, "WCF trip over the wire should have created a new object through serialisation");

            //Test that Get the saved booking works over WCF
            IEnumerable<Booking> actualBookings = null;
            waiter.Reset();
            _client.GetBookingsAsync(DateTime.Now, bookings =>
            {
                actualBookings = bookings;
                waiter.Set();
            });

            Assert.IsTrue(waiter.WaitOne(1000), "Timeout waiting for WCF asynk result");

            var retrievedBooking = actualBookings.FirstOrDefault();
            Assert.IsNotNull(retrievedBooking, "Bookings should contain created booking");
            Assert.AreEqual(testBooking.Id, retrievedBooking.Id, "Id is not persisted corectly");
            Assert.AreEqual(testBooking.ClientName, retrievedBooking.ClientName, "ClientName is not persisted corectly");
            Assert.AreEqual(testBooking.Duration, retrievedBooking.Duration, "Duration is not persisted corectly");
            Assert.AreEqual(testBooking.Slot, retrievedBooking.Slot, "Slot is not persisted corectly");
        }
예제 #26
0
파일: Program.cs 프로젝트: ssickles/archive
        static void Main()
        {
            try
            {
                waitHandle = new AutoResetEvent(false);
                
                DataAccess.CreateAndInsertTrackingProfile();
                using (WorkflowRuntime runtime = new WorkflowRuntime())
                {
                    SqlTrackingService trackingService = new SqlTrackingService(DataAccess.connectionString);

                    /*
                     *  Set partitioning settings on Sql Tracking Service and database
                     */

                    //Turn on PartitionOnCompletion setting-- Default is false
                    trackingService.PartitionOnCompletion = true;

                    //Set partition interval-- Default is 'm' (monthly)
                    DataAccess.SetPartitionInterval('d');

                    runtime.AddService(trackingService);
                    runtime.StartRuntime();

                    runtime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                    {
                       waitHandle.Set();
                    };
                    
                    runtime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
                    {
                        Console.WriteLine(e.Exception.Message);
                        waitHandle.Set();
                    };

                    WorkflowInstance instance = runtime.CreateWorkflow(typeof(SimpleWorkflow));
                    instance.Start();
                    waitHandle.WaitOne();

                    runtime.StopRuntime();
                    DataAccess.GetWorkflowTrackingEvents(instance.InstanceId);
                    Console.WriteLine("\nDone running the workflow.");

                    /*
                     *  Show tracking partition information and tables
                     */

                    DataAccess.ShowTrackingPartitionInformation();
                    DataAccess.ShowPartitionTableInformation();
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    Console.WriteLine(ex.InnerException.Message);
                else
                    Console.WriteLine(ex.Message);
            }
        }
예제 #27
0
        public bool TryProcess(CommandProcessorContext context, string[] args, out int exitCode)
        {
            var commandName = args[0].ToUpper();
            var commandArgs = args.Skip(1).ToArray();

            ICmdProcessor commandProcessor;
            if (!_processors.TryGetValue(commandName, out commandProcessor))
            {
                _log.Info("Unknown command: {0}.", commandName);
                if (_regCommandsProcessor != null)
                    _regCommandsProcessor.Execute(context, new string[0]);
                exitCode = 1;
                return false;
            }

            int exitC = 0;
            var executedEvent = new AutoResetEvent(false);

            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    var syntaxOk = commandProcessor.Execute(context, commandArgs);
                    if (syntaxOk)
                    {
                        exitC = context.ExitCode;
                    }
                    else
                    {
                        exitC = 1;
                        _log.Info("Usage of {0}:{1}{2}", commandName, Environment.NewLine, commandProcessor.Usage);
                    }
                    executedEvent.Set();
                }
                catch (Exception exc)
                {
                    _log.ErrorException(exc, "Error while executing command {0}.", commandName);
                    exitC = -1;
                    executedEvent.Set();
                }
            });

            executedEvent.WaitOne(1000);
            context.WaitForCompletion();

            if (!string.IsNullOrWhiteSpace(context.Reason))
                _log.Error("Error during execution of command: {0}.", context.Reason);
            if (context.Error != null)
            {
                _log.ErrorException(context.Error, "Error during execution of command");

                var details = new StringBuilder();
                BuildFullException(context.Error, details);
                _log.Error("Details: {0}", details.ToString());
            }
            
            exitCode = exitC == 0 ? context.ExitCode : exitC;
            return true;
        }
		public void MultipleSet ()
		{
			AutoResetEvent evt = new AutoResetEvent (true);
			Assertion.AssertEquals ("#01", true, evt.WaitOne (1000, false));
			evt.Set ();
			evt.Set ();
			Assertion.AssertEquals ("#02", true, evt.WaitOne (1000, false));
			Assertion.AssertEquals ("#03", false, evt.WaitOne (1000, false));
		}
예제 #29
0
		public void MultipleSet ()
		{
			AutoResetEvent evt = new AutoResetEvent (true);
			Assert.IsTrue (evt.WaitOne (1000, false), "#1");
			evt.Set ();
			evt.Set ();
			Assert.IsTrue (evt.WaitOne (1000, false), "#2");
			Assert.IsFalse (evt.WaitOne (1000, false), "#3");
		}
예제 #30
0
        static void Main(string[] args)
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
            host.Open();
            WriteLine("Host opened");

            ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
            ITest proxy = factory.CreateChannel();

            WriteLine("Add(4, 5): {0}", proxy.Add(4, 5));
            WriteLine("Add(4, 5): {0}", proxy.Add(4, 5));

            AutoResetEvent evt = new AutoResetEvent(false);
            proxy.BeginPower(2, 64, delegate(IAsyncResult asyncResult)
            {
                WriteLine("Pow(2, 64): {0}", proxy.EndPower(asyncResult));
                evt.Set();
            }, null);
            evt.WaitOne();

            proxy.BeginPower(2, 64, delegate(IAsyncResult asyncResult)
            {
                WriteLine("Pow(2, 64): {0}", proxy.EndPower(asyncResult));
                evt.Set();
            }, null);
            evt.WaitOne();

            WriteLine("Reverse(\"Hello world\"): {0}", proxy.Reverse("Hello world"));
            WriteLine("Reverse(\"Hello world\"): {0}", proxy.Reverse("Hello world"));

            int i;
            WriteLine("TryParseInt(123): {0}, {1}", proxy.TryParseInt("123", out i), i);
            WriteLine("TryParseInt(123): {0}, {1}", proxy.TryParseInt("123", out i), i);

            proxy.BeginTryParseDouble("34.567", delegate(IAsyncResult asyncResult)
            {
                double dbl;
                WriteLine("TryParseDouble(34.567): {0}, {1}", proxy.EndTryParseDouble(out dbl, asyncResult), dbl);
                evt.Set();
            }, null);
            evt.WaitOne();

            proxy.BeginTryParseDouble("34.567", delegate(IAsyncResult asyncResult)
            {
                double dbl;
                WriteLine("TryParseDouble(34.567): {0}, {1}", proxy.EndTryParseDouble(out dbl, asyncResult), dbl);
                evt.Set();
            }, null);
            evt.WaitOne();

            WriteLine("Press ENTER to close");
            Console.ReadLine();
            host.Close();
        }
예제 #31
0
        public static Control showAscxInForm(Type controlType, string formTitle, int width = -1, int height = -1, bool startHidden = false)
        {
            var controlCreation = new AutoResetEvent(false);
            Control control = null;
            O2Thread.staThread(
                ()=> {
                    O2Gui o2Gui = null;
                    try
                    {
                        control = (Control)PublicDI.reflection.createObjectUsingDefaultConstructor(controlType);
                        if (control != null)
                        {
                            control.Dock = DockStyle.Fill;
                            o2Gui = new O2Gui(width, height) ;        // I might need to adjust these width, height so that the control is the one with this size (and not the hosting form)
                            o2Gui.Text = formTitle;
                            if (width > -1)
                                control.Width = width;
                            else
                                o2Gui.Width = control.Width;            // if it is not defined resize the form to fit the control

                            if (height > -1)
                                control.Height = height;
                            else
                                o2Gui.Height = control.Height;          // if it is not defined resize the form to fit the control

                            o2Gui.clientSize(control.Width, o2Gui.Height);  // reset the form size to the control's size
                            o2Gui.Controls.Add(control);
                            o2Gui.Load += (sender, e) => controlCreation.Set();

                            if (startHidden)                         // very useful from UnitTests and cases where more should be added to the UI before showing it
                            {
                                o2Gui.Opacity = 0;
                                o2Gui.ShowInTaskbar = false;
                            }

                            o2Gui.showDialog(false);
                        }
                        else
                            controlCreation.Set();
                    }
                    catch (Exception ex)
                    {
                        "in showAscxInForm: {0}".format(ex).error();
                        controlCreation.Set();
                    }
                    finally
                    {
                        if (o2Gui != null)
                            o2Gui.Dispose();
                    }
                });
            var maxTimeOut = System.Diagnostics.Debugger.IsAttached ? -1 : 20000;
            if (controlCreation.WaitOne(maxTimeOut).failed())
                "[WinForms] Something went wrong with the creation of the {0} control with title '{1}' since it took more than 20s to start".error(controlType, formTitle);
            return control;
        }
 private void DrawRectangle()
 {
     autoResetEvent.WaitOne();
     Console.ForegroundColor = ConsoleColor.Blue;
     Console.WriteLine("  *****");
     Console.WriteLine("  *****");
     Console.WriteLine("  *****");
     Console.ResetColor();
     autoResetEvent.Set();
 }
예제 #33
0
        private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
        {
            if (useExpireFlag)
            {
                are.Set();
            }

            setTimer.Stop();
            setTimer.Enabled = false;
        }
예제 #34
0
        public void BeginRequest(RequestData data, HttpAsyncCallback callback, object state)
        {
            var request = WebRequest.CreateHttp(data.Request.Url);
            request.Method = data.Request.Method;
            //data.Request.BodySize;
            //data.Request.Comment;

            //data.Request.Cookies;
            //data.Request.Headers;
            //data.Request.HeadersSize;
            //data.Request.HttpVersion;
            //data.Request.PostData;
            //data.Request.QueryString;

            var gate = new AutoResetEvent(false);
            if (!string.IsNullOrEmpty(data.Request.PostData.Text))
            {

                request.BeginGetRequestStream(ar =>
                {
                    var postStream = request.EndGetRequestStream(ar);
                    byte[] byteArray = Encoding.UTF8.GetBytes(data.Request.PostData.Text);
                    postStream.Write(byteArray, 0, byteArray.Length);
                    postStream.Flush();

                    gate.Set();

                }, state);
            }
            else
            {
                gate.Set();
            }

            gate.WaitOne();

            var result = request.BeginGetResponse(ar =>
                {
                    var r = request.EndGetResponse(ar);
                    var s = r.GetResponseStream();
                    var d = ReadFully(s);
                    var txt = Encoding.UTF8.GetString(d, 0, d.Length);
                    data.Response = new Response()
                        {
                            Content = new Content()
                                {
                                    Text = txt
                                }
                        };
                    gate.Set();
                }, state);

            gate.WaitOne();

        }
예제 #35
0
        static void Main(string[] args)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);
            AutoResetEvent idleEvent = new AutoResetEvent(false);
            Dictionary<string, object> input = new Dictionary<string, object> { { "MaxNumber", 100 } };

            WorkflowApplication app = new WorkflowApplication(new SequentialNumberGuessWorkflow(), input);

            app.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                int Turns = Convert.ToInt32(e.Outputs["Turns"]);
                Console.WriteLine("Congratulations, you guessed the number in {0} turns", Turns);
                syncEvent.Set();
            };
            app.Aborted = delegate(WorkflowApplicationAbortedEventArgs e)
            {
                Console.WriteLine(e.Reason);
                syncEvent.Set();
            };

            app.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
            {
                Console.WriteLine(e.UnhandledException.ToString());
                syncEvent.Set();
                return UnhandledExceptionAction.Abort;
            };
            app.Idle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                idleEvent.Set();
            };

            app.Run();

            // Loop until the workflow completes.
            WaitHandle[] handles = new WaitHandle[] { syncEvent, idleEvent };
            while (WaitHandle.WaitAny(handles) != 0)
            {
                // Gather the user input and resume the bookmark.
                bool validEntry = false;
                while (!validEntry)
                {
                    int Guess;
                    if (!Int32.TryParse(Console.ReadLine(), out Guess))
                    {
                        Console.WriteLine("Please enter an integer.");
                    }
                    else
                    {
                        validEntry = true;
                        app.ResumeBookmark("EnterGuess", Guess);
                    }
                }
            }
        }
예제 #36
0
 private static void onCancel()
 {
     OpenRPA.Input.InputDriver.Instance.OnMouseDown -= onMouseDown;
     OpenRPA.Input.InputDriver.Instance.OnMouseUp   -= onMouseUp2;
     OpenRPA.Input.InputDriver.Instance.OnMouseMove -= onMouseMove;
     OpenRPA.Input.InputDriver.Instance.onCancel    -= onCancel;
     OpenRPA.Input.InputDriver.Instance.CallNext     = true;
     point = System.Drawing.Point.Empty;
     removeform();
     waitHandle.Set();
 }
예제 #37
0
        //public static System.Drawing.Point GetClick()
        //{
        //    createform();
        //    OpenRPA.Input.InputDriver.Instance.OnMouseDown += onMouseDown;
        //    OpenRPA.Input.InputDriver.Instance.OnMouseUp += onMouseUp2;
        //    OpenRPA.Input.InputDriver.Instance.OnKeyUp += OnKeyUp;

        //    waitHandle = new System.Threading.AutoResetEvent(false);
        //    waitHandle.WaitOne();
        //    return point;
        //}
        private static void OnKeyUp(Input.InputEventArgs e)
        {
            if (e.Key == Input.KeyboardKey.ESCAPE || e.Key == Input.KeyboardKey.ESC)
            {
                OpenRPA.Input.InputDriver.Instance.OnMouseDown -= onMouseDown;
                OpenRPA.Input.InputDriver.Instance.OnMouseUp   -= onMouseUp2;
                OpenRPA.Input.InputDriver.Instance.OnKeyUp     -= OnKeyUp;
                OpenRPA.Input.InputDriver.Instance.OnMouseMove -= onMouseMove;
                point = System.Drawing.Point.Empty;
                removeform();
                waitHandle.Set();
            }
        }
예제 #38
0
        /// <summary>
        /// Queries all privileges assigned to this universe.
        /// </summary>
        /// <returns>An enumerator returning KeyValuePairs of Account and Privileges. The entry can be orphaned, when the corresponding Account is null.</returns>
        public IEnumerable <KeyValuePair <Account, Privileges> > QueryPrivileges()
        {
            using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false))
            {
                List <KeyValuePair <uint, Privileges> > ids = new List <KeyValuePair <uint, Privileges> >();

                using (Session session = Server.connection.NewSession())
                {
                    Packet packet = session.Request;

                    packet.Command     = 0x44;
                    packet.BaseAddress = ID;

                    Server.connection.Send(packet);
                    Server.connection.Flush();

                    ThreadPool.QueueUserWorkItem(async delegate {
                        // I hate you for forcing me to do this, microsoft. Really.
                        packet = await session.Wait().ConfigureAwait(false);
                        are.Set();
                    });

                    are.WaitOne();

                    BinaryMemoryReader reader = packet.Read();

                    while (reader.Size > 0)
                    {
                        ids.Add(new KeyValuePair <uint, Privileges>(reader.ReadUInt32(), (Privileges)reader.ReadByte()));
                    }
                }

                Account account = null;

                foreach (KeyValuePair <uint, Privileges> kvp in ids)
                {
                    ThreadPool.QueueUserWorkItem(async delegate {
                        // I hate you for forcing me to do this, microsoft. Really.
                        account = (await Server.QueryAccount(kvp.Key).ConfigureAwait(false)) ?? new Account(Server, kvp.Key);
                        are.Set();
                    });

                    are.WaitOne();

                    yield return(new KeyValuePair <Account, Privileges>(account, kvp.Value));
                }
            }
        }
예제 #39
0
        private void CmdHandle(EquCYGCmd input)
        {
            Task task = new Task((state) =>
            {
                EquCYGCmd pCYGCmd = state as EquCYGCmd;
                OutputRunInfo(rtxtOutput, "处理命令,命令代码:" + pCYGCmd.CmdCode + "  编码:" + pCYGCmd.SampleCode);

                Thread.Sleep(5000);
                pCYGCmd.ResultCode = 1;
                pCYGCmd.FinishTime = DateTime.Now;
                pCYGCmd.DataFlag   = 1;
                this.EquDber.Update(pCYGCmd);
                OutputRunInfo(rtxtOutput, "取样成功,编码:" + pCYGCmd.SampleCode);
                EquCYGSample equcygsample = this.EquDber.Entity <EquCYGSample>(" where SampleCode='" + pCYGCmd.SampleCode + "'");
                if (equcygsample != null)
                {
                    equcygsample.SampleCode = "";
                    equcygsample.DataFlag   = 0;
                    this.EquDber.Update(equcygsample);
                }
                OutputRunInfo(rtxtOutput, "清理样柜成功,编码:" + pCYGCmd.SampleCode);
                autoResetEvent.Set();
            }, input);

            task.Start();
        }
예제 #40
0
        private static void Main(string[] args)
        {
            var taskOne = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("Task 1 is starting...");
                Thread.Sleep(5000);
                AutoResetEvent.Set();
                Console.WriteLine("Task 1 is completed.");
            });

            var taskTwo = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("Task 2 waiting for Task 1 to complete...");
                AutoResetEvent.WaitOne();
                Console.WriteLine("Task 2 is started...");
                Console.WriteLine("Waiting for AutoResetEvent to set...");
                AutoResetEvent.WaitOne();
            });


            taskTwo.Wait(); // taskTwo will never complete as its waiting for autoResetEvent to set, but no thread is executing and setting it.


            Console.ReadLine();
        }
예제 #41
0
 private void InterruptHendler(SimulatorEvents Interrupt, int info)
 {
     if (Interrupt == SimulatorEvents.CLOCK_INTERRUPT)
     {
         if (info == VAX11Simulator.Console.INIT_CLOCK)
         {
             InitClockInterrupt();
         }
         else if (info == VAX11Simulator.Console.ABORT_CLOCK)
         {
             AbortClockInterrupt();
         }
         else
         {
             throw new PanicException();
         }
     }
     else if (Interrupt == SimulatorEvents.POWER_DOWN_INTERRUPT)
     {
         //if we want to send event do it here.
         bConsoleClosed = true;
         BreakPointWait.Set();
         if (bInDebug && info == 1)
         {
             _theMainApplication.Invoke(new ProgramEndHandler(_theMainApplication.InterfaceDoRestartDebuggedProgram), new object[] { "Program ended because Console has been closed" });
         }
     }
     else
     {
         theSimulator.SendEvent(Interrupt, info);
     }
 }
예제 #42
0
        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);
        }
예제 #43
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);
        }
예제 #44
0
 public TcpNotifyServer()
 {
     queue.callback = () =>
     {
         ARE.Set();
     };
 }
예제 #45
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();//不会等待子线程的结束
                }
            });
        }
예제 #46
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"));
        }
예제 #47
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);
         }
     }
 }
예제 #48
0
 private void ProcessQueue(object sender, Timers.ElapsedEventArgs e)
 {
     while (messageQueue.Count != 0)
     {
         var msg = (Datagram)null;
         if (!messageQueue.TryPeek(out msg))
         {
             continue;
         }
         if (msg != null && (running || msg.Sticky))
         {
             msg.Send();
             if (msg.SendCount > DATAGRAMS_PER_MESSAGE)
             {
                 messageQueue.TryDequeue(out msg);
             }
             break;
         }
         else
         {
             messageQueue.TryDequeue(out msg);
         }
     }
     datagramPosted.Set();
     queueTimer.Enabled  = messageQueue.Count != 0;
     queueTimer.Interval = random.Next(25, running ? 75 : 50);
 }
예제 #49
0
        private async Task ExecCommandRun(RoutedEventArgs e)
        {
            if (ActiveDocument != null)
            {
                if (IsPaused)
                {
                    ActiveDocument.RemoveExecutingMarker();
                    IsPaused = false;
                    m_BreakPointLock.Set();
                }
                else
                {
                    IsBuilding = true;
                    UpdateLayout();

                    var fileName = ActiveDocument.DocumentFileName;
                    await Task.Run(delegate
                    {
                        var bSucComp = m_VM.compilestatic(new string[] { fileName }, "test", true);
                        m_VM.pushroottable();
                        var bSucCall = m_VM.call(1, false, true);
                    });

                    IsBuilding = false;
                }
                UpdateLayout();
            }
        }
예제 #50
0
 internal void Trigger()
 {
     while (isReadyForEvent == false)
     {
         System.Threading.Thread.Sleep(0);
     }
     auto_event.Set();
 }
예제 #51
0
 private void RequestWait()
 {
     if (waiting)
     {
         throw new InternalError();
     }
     Report.Debug(DebugFlags.Wait, "Signalling wait event");
     wait_event.Set();
 }
 public void Shutdown(object owner, bool continueExistingPeriodicTasks, bool executeExistingDelayedTasks)
 {
     if (!executeExistingDelayedTasks)
     {
         lock (tasks) {
             for (int n = 0; n < tasks.Count; n++)
             {
                 IScheduledITask t = tasks [n];
                 if (t.Owner == owner)
                 {
                     tasks.RemoveAt(n);
                     n--;
                 }
             }
             newTask.Set();
         }
     }
 }
예제 #53
0
 protected override void Dispose(bool disposing)
 {
     if (!disposed)
     {
         disposed = true;
         GameInstance.Components.Remove(this);
         if (ownsServices)
         {
             GameInstance.Components.Remove(services);
             services.Dispose();
         }
         todo.Set();
         thread.Join();
         todo.Close();
         thread = null;
         todo   = null;
     }
 }
예제 #54
0
 /// <summary>
 /// Clean up any resources being used. and stop events
 /// </summary>
 protected override void Dispose(bool disposing)
 {
     if (bNowExiting)
     {
         eWaitForInput.Set();
     }
     if (bTextMode)
     {
         caretThread.Abort();
     }
     if (disposing)
     {
         if (components != null)
         {
             components.Dispose();
         }
     }
     base.Dispose(disposing);
 }
예제 #55
0
        private void download_completed(object sender)
        {
            lock (locker)
            {
                download_file current = (download_file)sender;
                Console.SetCursorPosition(0, current.ConsoleLine);
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.ForegroundColor = current.Error == null ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed;
                Console.WriteLine(
                    string.Format("{0,5}  -> {4,14}{3,8}  {1,-30}  {2,-30}",
                                  getIcon(current.Status),
                                  current.FileName,
                                  current.Error == null ? "" : string.Format("Error: {0}", current.Error.Message),
                                  ContentSizeToStr(current.ContentBytes),
                                  string.Empty
                                  )
                    .PadRight(Console.WindowWidth - 1));
                Console.ResetColor();
                total_bytes += current.ContentBytes;

                if (current.Error != null)
                {
                    ErrorList += string.Format("{0,5}File: {1}\n{0,5}Error message: {2}\n\n",
                                               " ",
                                               current.FileName,
                                               current.Error.Message + (current.Error.InnerException != null ? ("\nInnerMessage: " + current.Error.InnerException.Message) : ""));
                }
            }
            download_file _current = (download_file)sender;

            //check to finish
            if (started_count == files.Count() &&
                downloader.Where(x => x.Status == DownloadFileStatus.SUCCESS ||
                                 x.Status == DownloadFileStatus.ERROR).Count() == parallel_count)
            {
                Console.SetCursorPosition(0, downloader.Max(x => x.ConsoleLine) + 2);
                Console.ResetColor();
                Console.WriteLine(" -------------------------\n");

                if (ErrorList != null)
                {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine(ErrorList);
                    Console.ResetColor();
                    Console.WriteLine(" -------------------------");
                }

                resetEvent.Set();
            }
            else if (started_count != files.Count())
            {
                _current.download(files[started_count], process_line_start + started_count);
                started_count++;
            }
        }
예제 #56
0
 static internal void ClearAutoEvents()
 {
     lock (_sLockObj)
     {
         while (_AutoEventQueue.Count > 0)
         {
             System.Threading.AutoResetEvent aEvent = _AutoEventQueue.Dequeue();
             aEvent.Set();
         }
     }
 }
        public void Foo(Action printFoo)
        {
            for (int i = 0; i < n; i++)
            {
                slim1.WaitOne();
                // printFoo() outputs "foo". Do not change or remove this line.
                printFoo();

                slim2.Set();
            }
        }
예제 #58
0
 public void UnInit()
 {
     try
     {
         at_stinterval.Set();
         LogManager.WriteLog("StackerServiceHandle Thread Stoped ", LogManager.enumLogLevel.Info);
     }
     catch (Exception ex)
     {
         ExceptionManager.Publish(ex);
     }
 }
예제 #59
0
        void CloseCamera()
        {
            if (_ptGreyCamera != null)
            {
                _ptGreyCamera.Close();
            }

            if (_ptGreyStopImageThreadEvent != null)
            {
                _ptGreyStopImageThreadEvent.Set();
            }
        }
예제 #60
0
        static void Add(object data)
        {
            if (data is AddParams)
            {
                Console.WriteLine($"ID of thread in Add(): {Thread.CurrentThread.ManagedThreadId}");

                AddParams ap = (AddParams)data;
                Console.WriteLine($"{ap.a} + {ap.b} is {ap.a + ap.b}");

                waitHandle.Set();
            }
        }