Example #1
0
        internal CommandResult StartOperation(ThreadingModel model, SingleSteppingEngine caller)
        {
            if (!ThreadManager.InBackgroundThread)
            {
                throw new InternalError();
            }

            if ((current_state != ProcessState.Stopped) && (current_state != ProcessState.SingleThreaded))
            {
                throw new TargetException(TargetError.NotStopped);
            }

            if ((model & ThreadingModel.ThreadingMode) == ThreadingModel.Single)
            {
                current_state = ProcessState.SingleThreaded;
                if ((model & ThreadingModel.ResumeThreads) != 0)
                {
                    ResumeUserThreads(model, caller);
                }
                return(new ThreadCommandResult(caller.Thread));
            }
            else if ((model & ThreadingModel.ThreadingMode) != ThreadingModel.Process)
            {
                throw new ArgumentException();
            }

            lock (this) {
                current_state = ProcessState.Running;
                stopped_event.Reset();
                current_operation = new ProcessCommandResult(this, model);
            }

            ResumeUserThreads(model, caller);
            return(current_operation);
        }
        /// <summary>
        /// 启动发送任务
        /// </summary>
        /// <param name="studyInstUID"></param>
        /// <param name="accepteNums"></param>
        public bool StartDownload(string studyInstUID)
        {
            var ok = false;

            try
            {
                var cd = DateTime.Now;

                DownloadItem di = new DownloadItem()
                {
                    Completed        = 0,
                    SendStatus       = E_SendStatus.Start,
                    StudyInstanceUID = studyInstUID
                                       //  Completed = 0,
                                       // Fails = 0,
                                       // Warnings = 0,
                                       //  AddTime = cd,
                                       //TokenTime = cd,
                                       //   PatientId = patientId,
                                       //  Remaings = 0
                };
                mr.WaitOne();
                mr.Reset();
            }
            catch (Exception e)
            {
            }
            finally
            {
                mr.Set();
            }
            return(ok);
        }
Example #3
0
        internal object SendCommand(SingleSteppingEngine sse, TargetAccessDelegate target,
                                    object user_data)
        {
            Command command = new Command(sse, target, user_data);

            if (!engine_event.WaitOne(WaitTimeout, false))
            {
                throw new TargetException(TargetError.NotStopped);
            }

            event_queue.Lock();
            engine_event.Reset();

            current_command = command;

            event_queue.Signal();
            event_queue.Unlock();

            engine_event.WaitOne();

            if (command.Result is Exception)
            {
                throw (Exception)command.Result;
            }
            else
            {
                return(command.Result);
            }
        }
Example #4
0
        public void CallbackInvokedMultipleTimes()
        {
            var reRegisterForFinalize = true;
            var callbackInvoked = new ManualResetEvent(false);
            GcNotification.Register(state =>
            {
                callbackInvoked.Set();
                return reRegisterForFinalize;
            }, null);

            GcCollectAndWait();
            Assert.True(callbackInvoked.WaitOne(0));

            callbackInvoked.Reset();
            reRegisterForFinalize = false;

            GcCollectAndWait();
            Assert.True(callbackInvoked.WaitOne(0));

            callbackInvoked.Reset();

            // No callback expected the 3rd time
            GcCollectAndWait();
            Assert.False(callbackInvoked.WaitOne(0));
        }
        public void CallbackInvokedMultipleTimes()
        {
            int callbackCount = 0;
            var callbackInvoked = new ManualResetEvent(false);
            GcNotification.Register(state =>
            {
                callbackCount++;
                callbackInvoked.Set();
                if (callbackCount < 2)
                {
                    return true;
                }
                return false;
            }, null);

            GC.Collect(2, GCCollectionMode.Forced, blocking: true);
            Assert.True(callbackInvoked.WaitOne(100));
            Assert.Equal(1, callbackCount);

            callbackInvoked.Reset();

            GC.Collect(2, GCCollectionMode.Forced, blocking: true);
            Assert.True(callbackInvoked.WaitOne(100));
            Assert.Equal(2, callbackCount);

            callbackInvoked.Reset();

            // No callback expected the 3rd time
            GC.Collect(2, GCCollectionMode.Forced, blocking: true);
            Assert.False(callbackInvoked.WaitOne(100));
            Assert.Equal(2, callbackCount);
        }
Example #6
0
        /// -------------------------------------------------------------------
        /// <summary>
        /// Called by the test cases to make sure the number of desired events have been fired before they start doing eny event verification.
        /// </summary>
        /// -------------------------------------------------------------------
        internal static bool WaitForEvents(int number, int millSeconds)
        {
            int time = (number * millSeconds);

            Comment("Waiting for a period of " + time + " milliseconds for no events to occur");

            _waitedForEventToFire = true;

            _lastEvent = DateTime.Now;

            // Wait for a specific time span since the last event occured before
            // return back to the calling test.
            while (((DateTime.Now.Ticks - _lastEvent.Ticks) / TimeSpan.TicksPerMillisecond) < time)
            {
                // _haveNotifiedEvent.Set() will let OnEvent() process events if it has stoped processing at the _haveNotifiedEvent.WaitOne() call.
                _haveNotifiedEvent.Set();

                // Wait until OnEvent() has called _gotNotifiedEvent.Set() or the amount of time defined by millSeconds has expired, which ever comes first.
                _gotNotifiedEvent.WaitOne(millSeconds, true);

                // Reset so _gotNotifiedEvent.Wait() will pause on the next iteration.
                _gotNotifiedEvent.Reset();
            }

            int count = _eventList == null ? 0 : _eventList.Count;

            Comment("Stop waiting for events.  Found " + count + " event(s)");
            //RemoveAllEventHandlers();
            //Thread.Sleep(1);
            return(count == number);
        }
Example #7
0
        public void Stop()
        {
            if (!IsStarted)
            {
                string message = "Not started!";
                Logging.Log(message);
                return;
            }

            assembly = null;

            // signal that we want to shutdown our server socket.
            // this should start the process of stopping the background thread
            if (serversocket != null)
            {
                Logging.Log("Socket will be shutdown.");
                serversocket.Close();
            }
            // even if the thread doesn't shutdown, we may be able to start
            // another mainthread
            started.Reset();
            // if we have a background thread
            if (mainthread != null)
            {
                // wait a little bit
                if (!mainthread.Join(Timeout))
                {
                    // if the thread did not shutdown, be nasty about it.
                    Logging.Log("Timeout waiting for thread to complete!");
                    mainthread.Abort();
                }
            }
            SetStatus("Stopped");
        }
Example #8
0
        /// <summary>
        /// 初始化命令
        /// </summary>
        public void Init()
        {
            ManagerPlant.flowManager.InitPos();
            XmlNode    cmdNode = xd.SelectSingleNode("Cmds/Cmd/DispatchCmd[@strMemo='初始化加样臂']");
            XmlElement el      = cmdNode as XmlElement;

            WaitEvent.Reset();
            ManagerPlant.aiKangManager.ClsModule.SendXmlElement(el, "Module_AiKang_Service");
            WaitEvent.WaitOne();
        }
Example #9
0
            public void ExecuteCommand(Command command)
            {
                lock (this) {
                    this.command      = command;
                    this.last_command = command;
                    this.repeating    = false;

                    completed_event.Reset();
                    command_event.Set();
                }
            }
        public void TestSuccesfulConnection()
        {
            // setup
            Uri url = new Uri("http://test.com");
            CancellationTokenSource cts = new CancellationTokenSource();
            List<EventSourceState> states = new List<EventSourceState>();
            ServiceResponseMock response = new ServiceResponseMock(url, System.Net.HttpStatusCode.OK);
            WebRequesterFactoryMock factory = new WebRequesterFactoryMock(response);
            ManualResetEvent stateIsOpen = new ManualResetEvent(false);

            TestableEventSource es = new TestableEventSource(url, factory);
            es.StateChanged += (o, e) =>
            {
                states.Add(e.State);
                if (e.State == EventSourceState.OPEN)
                {
                    stateIsOpen.Set();
                    cts.Cancel();
                }
            };


            // act
            stateIsOpen.Reset();

            es.Start(cts.Token);

            stateIsOpen.WaitOne();

            // assert
            Assert.IsTrue(states.Count == 2);
            Assert.AreEqual(states[0], EventSourceState.CONNECTING);
            Assert.AreEqual(states[1], EventSourceState.OPEN);
        }
Example #11
0
		public MockPresenter(Page.ePageType activePageType = Page.ePageType.AVItemCollectionGallery,
			string excludedTitles = "Popular,TV,V,W,Sports,ESPN,News",
			int imageWidth = IMAGE_WIDTH, int imageHeight = IMAGE_HEIGHT)
		{
			// start logging during mocking
			SetupLogging();

			_model = MediaServerModel.GetInstance();

			TitlesExcludedFromImageReplacement = excludedTitles;
			ImageWidth = imageWidth;
			ImageHeight = imageHeight;

			AVItemCollections = new ObservableCollection<UPnPCollection>();
			AVItems = new ObservableCollection<UPnPItem>();
			DetailItem = new ObservableCollection<UPnPItem>();
			Items = new ObservableCollection<AVItemBase>();

			_allDoneEvent = new ManualResetEvent(false);
			Logger.TraceInfo(MethodBase.GetCurrentMethod(), "MockPresenter _model: {0}", _model.Actions.ContentDirectory.Name);
			_model.Actions.ContentDirectory.NewDeviceFound += NewDeviceFound;
			_model.Actions.ContentDirectory.OnCreateControlPoint(null);
			_allDoneEvent.WaitOne();
			_allDoneEvent.Reset();
			WaitTimeBetweenGetImageInMilliseconds = 0;
			StartBackgroundThreadToGetImages();
			PropertyChanged += OnLocalPropertyChanged;

			// default to the showing a collection
			ActivePageType = activePageType;
			//ActivePageType = Page.ePageType.AVItemGallery;
			//ActivePageType = Page.ePageType.AVItemDetails;

			_allDoneEvent.WaitOne(TimeSpan.FromSeconds(15D));
		}
Example #12
0
            void command_thread_main()
            {
                Report.Debug(DebugFlags.CLI, "{0} starting command thread", this);

                while (!Completed)
                {
                    command_event.WaitOne();

                    Report.Debug(DebugFlags.CLI, "{0} command thread waiting", this);

                    Command command;
                    lock (this) {
                        command      = this.command;
                        this.command = null;

                        command_event.Reset();
                    }

                    Report.Debug(DebugFlags.CLI, "{0} command thread execute: {1}", this, command);

                    execute_command(command);

                    Report.Debug(DebugFlags.CLI, "{0} command thread done executing: {1}", this, command);

                    completed_event.Set();
                }

                Report.Debug(DebugFlags.CLI, "{0} terminating command thread", this);
            }
Example #13
0
        void processAction()
        {
            while (!_exited || _backupQueue.Count > 0)
            {
                _backupEvent.WaitOne();
                _backupEvent.Reset();

                List <ContentAction> buffer = new List <ContentAction>(500);
                while (true)
                {
                    if (_backupQueue.TryDequeue(out ContentAction dataitem))
                    {
                        buffer.Add(dataitem);
                    }
                    else
                    {
                        break;
                    }
                }

                if (buffer.Count > 0)
                {
                    _db.Handle(buffer);
                }
            }
        }
Example #14
0
		public void Connect(string address, int port)
		{
			if (socket == null)
			{
				Id = -1;
				this.address = address;
				this.port = port;

				using (mreBeginConnect = new ManualResetEvent(false))
				{
					mreBeginConnect.Reset();
					BeginConnect();
					mreBeginConnect.WaitOne();
				}

				if (!closed)
				{
					InitSocket();

					OnConnected();
				}
				else
				{
					OnDisconnected();
				}
			}
		}
Example #15
0
        public static void RunTaskWaitAndDoEvents(ThreadStart methodToInvoke, int pollTimeMs)
        {
            var syncEvent = new ManualResetEvent(true);

            syncEvent.Reset();

            ThreadPool.QueueUserWorkItem(
                delegate(object state)
                {
                    try
                    {
                        methodToInvoke();
                    }
                    finally
                    {
                        syncEvent.Set();
                    }
                });

            do
            {
                bool releaded = syncEvent.WaitOne(pollTimeMs);

                if (releaded)
                    break;

                Application.DoEvents();
            }
            while (true);
        }
        public static void Run()
        {
            // ExStart:SupportIMAPIdleCommand
            // Connect and log in to IMAP 
            ImapClient client = new ImapClient("imap.domain.com", "username", "password");

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            ImapMonitoringEventArgs eventArgs = null;
            client.StartMonitoring(delegate(object sender, ImapMonitoringEventArgs e)
            {
                eventArgs = e;
                manualResetEvent.Set();
            });
            Thread.Sleep(2000);
            SmtpClient smtpClient = new SmtpClient("exchange.aspose.com", "username", "password");
            smtpClient.Send(new MailMessage("*****@*****.**", "*****@*****.**", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
            manualResetEvent.WaitOne(10000);
            manualResetEvent.Reset();
            Console.WriteLine(eventArgs.NewMessages.Length);
            Console.WriteLine(eventArgs.DeletedMessages.Length);
            client.StopMonitoring("Inbox");
            smtpClient.Send(new MailMessage("*****@*****.**", "*****@*****.**", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
            manualResetEvent.WaitOne(5000);
            // ExEnd:SupportIMAPIdleCommand
        }
Example #17
0
        private async void TheGame_Load(object sender, EventArgs e)
        {
            MessageBox.Show("Choose a number between 1 and 128 & Keep it in your mind", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
            for (cardno = 0; cardno <= 6; cardno++)
            {
                noperrow = 0;
                for (number = 1; number <= 127; number++)
                {
                    if (Convert.ToBoolean(number & (int)Math.Pow(2.0, cardno)))
                    {
                        label1.Text += number + "    ";
                        noperrow++;

                        if (noperrow == 5)
                        {
                            label1.Text += "\n";
                            noperrow     = 0;
                        }
                    }
                }
                if (noperrow < 5)
                {
                    label1.Text += "\n";
                }
                mre.Reset();
                await Task.Factory.StartNew(() => { mre.WaitOne(); });
            }
            MessageBox.Show("Your Number is : " + chno.ToString() + "   :D <3", "The answer", MessageBoxButtons.OK, MessageBoxIcon.Information);
            StartPage f = new StartPage();

            f.Show();
            this.Hide();
        }
Example #18
0
        public XSocketLogListener(String host)
        {
            ThreadStart connect = () =>
            {
                myEvent = new ManualResetEvent(false);
                mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                SocketAsyncEventArgs connArg = new SocketAsyncEventArgs();
                // Ҫ���ӵ�Զ�̷�����
                connArg.RemoteEndPoint = new DnsEndPoint(host, HOST_PORT,AddressFamily.InterNetwork);

                connArg.Completed += (sendObj, arg) =>
                {
                    if (arg.SocketError == SocketError.Success) //���ӳɹ�
                    {
                        XLog.WriteInfo("SocketLogServer Connect Success");
                    }
                    else
                    {
                        XLog.WriteInfo("SocketLogServer Connect fail");
                        mySocket.Close();
                        mySocket = null;
                    }
                    // ������̱߳����������
                    myEvent.Set();
                };

                myEvent.Reset();
                mySocket.ConnectAsync(connArg);
                myEvent.WaitOne(TIME_OUT);
            };

            new Thread(connect).Start();
        }
Example #19
0
 public void SharedTimer_Register_CallbackInvokedMultipleTimes()
 {
     var timerSet = new ManualResetEvent(false);
     using (var timer = new SharedTimer(TimeSpan.FromMilliseconds(20)))
     {
         using (IDisposable cleanup = timer.Register(_ => timerSet.Set(), null))
         {
             Assert.NotNull(cleanup);
             Assert.True(timerSet.WaitOne(500));
             timerSet.Reset();
             Assert.True(timerSet.WaitOne(500));
             timerSet.Reset();
         }
         Assert.False(timerSet.WaitOne(500));
     }
 }
Example #20
0
		/// <summary>
		/// Start server and begin accepting clients
		/// </summary>
		public static void Start()
		{
			futureMoves = new Queue<FutureMove>();
			clientsPlaying = new List<Connection>();
			clientUpdate = new List<Connection>();
			clientAI = new List<Connection>();
			clientPlayers = new List<Connection>();
			clientsAll = new List<Connection>();
			updateTimer.Elapsed += new ElapsedEventHandler(UpdateTick);
			updateTimer.AutoReset = false;
			if (listener != null) listener.Stop();
			listener = TcpListener.Create(Program.port);
			listener.Start();
			allDone = new ManualResetEvent(false);
			try
			{
				while (true)
				{
					allDone.Reset();
					listener.BeginAcceptTcpClient(new AsyncCallback(AcceptTcpClient), listener);
					allDone.WaitOne();
				}
			}
			catch (ThreadAbortException)
			{
				listener.Stop();
			}
		}
        public void TestAsyncGetAccountInfo_WhenUserIsNotLoggedIn_ThenStatusIsNotLoggedIn()
        {
            const int status = 847587532;
            ManualResetEvent wait = new ManualResetEvent(false);
            bool callbackWasExecuted = false;

            OperationFinished<GetAccountInfoResponse> callback = resp =>
                                                                 	{
                                                                        Assert.AreEqual(GetAccountInfoStatus.NotLoggedIn, resp.Status);

                                                                        Assert.IsInstanceOf(typeof(int), resp.UserState);
                                                                        Assert.AreEqual(status, (int)resp.UserState);

                                                                        Assert.IsNull(resp.Error);
                                                                        Assert.IsNull(resp.User);

                                                                 		callbackWasExecuted = true;

                                                                 		wait.Reset();
                                                                 	};

            Context.Manager.Logout();

            Context.Manager.GetAccountInfo(callback, status);

            wait.WaitOne(30000);

            Assert.IsTrue(callbackWasExecuted, "Callback was not executed. The operation has timed out");
        }
        public void TestAsyncGetAccountInfo()
        {
            const int status = 847587532;
            ManualResetEvent wait = new ManualResetEvent(false);
            bool callbackWasExecuted = false;

            OperationFinished<GetAccountInfoResponse> callback = resp =>
                                                                 	{
                                                                 		Assert.AreEqual(GetAccountInfoStatus.Successful, resp.Status);
                                                                 		Assert.IsNull(resp.Error);
                                                                 		Assert.IsInstanceOf(typeof(int), resp.UserState);
                                                                        Assert.AreEqual(status, (int)resp.UserState);

                                                                        Assert.IsNotNull(resp.User);

                                                                        Assert.AreEqual(Context.AuthenticatedUser.AccessID, resp.User.AccessID);
                                                                        Assert.AreEqual(Context.AuthenticatedUser.ID, resp.User.ID);
                                                                        Assert.AreEqual(Context.AuthenticatedUser.MaxUploadSize, resp.User.MaxUploadSize);
                                                                        Assert.AreEqual(Context.AuthenticatedUser.SpaceAmount, resp.User.SpaceAmount);
                                                                        Assert.AreEqual(Context.AuthenticatedUser.SpaceUsed, resp.User.SpaceUsed);

                                                                        StringAssert.IsMatch(Context.AuthenticatedUser.Email, resp.User.Email);
                                                                        StringAssert.IsMatch(Context.AuthenticatedUser.Login, resp.User.Login);

                                                                 		callbackWasExecuted = true;

                                                                 		wait.Reset();
                                                                 	};

            Context.Manager.GetAccountInfo(callback, status);

            wait.WaitOne(30000);

            Assert.IsTrue(callbackWasExecuted, "Callback was not executed. The operation has timed out");
        }
Example #23
0
        public ContentLoader(ContentLoaderProgressHandler progress)
        {
            LoaderQueue = new Queue<ContentLoaderItem>();
            ContinueLoaderThreadEvent = new ManualResetEvent(false);

            ContentLoaderThread = new Thread(delegate() {
                double itemIndex = 0;

                while (ContentLoaderThread.ThreadState != ThreadState.Aborted)
                {
                    if (LoaderQueue.Count > 0)
                    {                        
                        ContentLoaderItem item = LoaderQueue.Dequeue();
                        progress((++itemIndex) / (itemIndex + LoaderQueue.Count), item.Description);
                        item.Handler(item.Target);
                    }
                    else 
                    {
                        ContinueLoaderThreadEvent.WaitOne();
                    }
                    ContinueLoaderThreadEvent.Reset();
                }              
            });
            ContentLoaderThread.Start();
        }
Example #24
0
        void backupRunning()
        {
            while (!_disposed || _backupQueue.Count > 0)
            {
                _backupEvent.WaitOne();
                _backupEvent.Reset();

                List <OpAction <T> > buffer = new List <OpAction <T> >(500);
                while (true)
                {
                    if (_backupQueue.TryDequeue(out OpAction <T> dataitem))
                    {
                        buffer.Add(dataitem);
                    }
                    else
                    {
                        break;
                    }
                }

                if (buffer.Count > 0)
                {
                    _db.Handle(buffer);
                }
            }
            _backupExited = true;
        }
Example #25
0
        public new void ReInitialize(IProtocol !protocol)
        {
            base.ReInitialize(protocol);
            sessionTCB          = new TCB();
            sessionTCB.SND.WND  = TcpFormat.TCP_MSS;
            sessionTCB.RCV.WND  = TcpFormat.TCP_MSS;
            maxAcceptedSessions = 0;
            passiveSession      = null;
            isValidForRead      = true;
            isValidForWrite     = true;

            DrainQueue(outQueue);
            DrainQueue(inQueue);
            retransmitQ.Clear();
            acceptedSessions.Clear();
            setupCompleteEvent.Reset();
            closedEvent.Reset();

            // create and initialize the init state
            this.oldStateEnum = TcpStateEnum.Undefined;
            if (!IsClosed)
            {
                ChangeState(TCPFSM.CLOSED);
            }

            DestroyConnectTimer();
            DestroyShutdownTimer();
            DestroyPersistTimer();

            retransInterval = InitialRetransInterval;
        }
        bool isKeyPressed = false; //KeyDown fires many times, possible bug in Eto.Forms ?

        /// <summary>
        /// Creates new image display form supporting rectangle creation.
        /// </summary>
        /// <param name="title">Window title.</param>
        /// <param name="setPassingResetEvent">True to set the reset event to passing state, false otherwise.</param>
        public DrawingRectangleForm(string title = "", bool setPassingResetEvent = true)
            :base(title)
        {      
            adorner = new DrawingRectangleAdorner(PictureBox);
            adorner.OnDrawn = () => 
            {
                if (OnDrawn != null && !Rectangle.IsEmpty) OnDrawn(Rectangle);
                adorner.Clear();
            };

            ResetEvent = new ManualResetEvent(setPassingResetEvent);

            KeyDown += (s, e) =>
            {
                if (isKeyPressed) return;
                isKeyPressed = true;

                ResetEvent.Reset();
            };
            KeyUp += (s, e) =>
            {
                isKeyPressed = false;
                ResetEvent.Set();
            };
        }
Example #27
0
        public static void Test(ITransport t, IQueueStrategy strategy,
            Endpoint queueEndpoint, Action<Message> send, Func<MessageEnumerator>
            enumer)
        {
            Guid id = Guid.NewGuid();
            var serializer = new XmlMessageSerializer(new
                                                          DefaultReflection(), new DefaultKernel());

            var subscriptionStorage = new MsmqSubscriptionStorage(new
                                                                      DefaultReflection(),
                                                                  serializer,
                                                                  queueEndpoint.Uri,
                                                                  new
                                                                      EndpointRouter(),
                                                                  strategy);
            subscriptionStorage.Initialize();

            var wait = new ManualResetEvent(false);

            subscriptionStorage.SubscriptionChanged += () => wait.Set();

            t.AdministrativeMessageArrived +=
                subscriptionStorage.HandleAdministrativeMessage;

            Message msg = new MessageBuilder
                (serializer).GenerateMsmqMessageFromMessageBatch(new
                                                                     AddInstanceSubscription
                {
                    Endpoint = queueEndpoint.Uri.ToString(),
                    InstanceSubscriptionKey = id,
                    Type = typeof (TestMessage2).FullName,
                });
            send(msg);

            wait.WaitOne();

            msg = new MessageBuilder
                (serializer).GenerateMsmqMessageFromMessageBatch(new
                                                                     RemoveInstanceSubscription
                {
                    Endpoint = queueEndpoint.Uri.ToString(),
                    InstanceSubscriptionKey = id,
                    Type = typeof (TestMessage2).FullName,
                });

            wait.Reset();

            send(msg);

            wait.WaitOne();

            IEnumerable<Uri> uris = subscriptionStorage
                .GetSubscriptionsFor(typeof (TestMessage2));
            Assert.Equal(0, uris.Count());

            int count = 0;
            MessageEnumerator copy = enumer();
            while (copy.MoveNext()) count++;
            Assert.Equal(0, count);
        }
Example #28
0
 /// <summary>
 /// pauses the encoding process
 /// </summary>
 /// <param name="error">output for any errors that might ocurr during this method</param>
 /// <returns>true if encoding has been successfully paused, false if not</returns>
 public void pause()
 {
     if (!mre.Reset())
     {
         throw new JobRunException("Could not reset mutex");
     }
 }
Example #29
0
        static void Main()
        {
            // Creates a new ExamplePenguin class which, in this instance, is a wrapper for Sharpenguin.
            ExamplePenguin myPenguin = new ExamplePenguin();

            // Creates a new ManualResetEvent. This is used to pause the thread so that the program doesn't exit.
            Threads.ManualResetEvent penguinDone = new Threads.ManualResetEvent(false);
            // Asks for the user's username.
            System.Console.Write("Enter your username: "******"Enter your password: "******"Enter the name of the server to join: ");
            string joinServer = System.Console.ReadLine();

            // Connects the penguin.
            myPenguin.Connect(penguinUsername, penguinPassword, joinServer);
            // Pauses the thread. [penguinDone.Set() would resume the thread, and so would exit the program.]
            penguinDone.Reset();
            penguinDone.WaitOne();
        }
Example #30
0
        public static void Main2(string[] args)
        {
            ManualResetEvent conn = new ManualResetEvent(false);
            int count = 0;
            Socket main = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint bindingPoint = new IPEndPoint(IPAddress.Any,6199);
            main.Bind(bindingPoint);
            main.Listen(10);
            Console.WriteLine("main socket status: Blocking:{0}, localIP:{1}", main.Blocking, main.LocalEndPoint.ToString());
            do
            {

                conn.Reset();
                lock (main)
                {
                    count++;
                }
                main.BeginAccept(AceptCallback, new stateObj { sck = main, ClientNo = count, conn = conn });
                Console.WriteLine("wait one : " + count);
                conn.WaitOne();
            }
            while (true);
            Console.ReadKey();
            main.Close(1000);
        }
        public void TestAsyncGetTicket()
        {
            BoxManager manager = new BoxManager(ApplicationKey, ServiceUrl, null);
            const int someValue = 78435;
            ManualResetEvent wait = new ManualResetEvent(false);
            bool callbackWasExecuted = false;

            OperationFinished<GetTicketResponse> response = resp =>
                                                                {
                                                                    Assert.IsNull(resp.Error);
                                                                    Assert.IsNotNull(resp.Ticket);
                                                                    Assert.IsInstanceOfType(typeof(int), resp.UserState);
                                                                    Assert.AreEqual(GetTicketStatus.Successful,  resp.Status);

                                                                    int userStatus = (int) resp.UserState;
                                                                    Assert.AreEqual(someValue, userStatus);

                                                                    callbackWasExecuted = true;

                                                                    wait.Reset();
                                                                };

            manager.GetTicket(response, someValue);

            wait.WaitOne(30000);

            Assert.IsTrue(callbackWasExecuted, "Callback was not executed. The operation has timed out");
        }
        public void start_and_callback()
        {
            var reset = new ManualResetEvent(false);

            var timer = new DefaultTimer();

            int i = 0;

            timer.Start(() => {
                i++;
                reset.Set();
                timer.Stop();
            }, 500);

            reset.WaitOne(1000);

            i.ShouldBe(1);

            // Should only fire once because timer.Stop was called
            reset.Reset();
            reset.WaitOne(1000);

            i.ShouldBe(1);

            timer.Dispose();
        }
		public void AcceptAsyncShouldUseAcceptSocketFromEventArgs()
		{
			var readyEvent = new ManualResetEvent(false);
			var mainEvent = new ManualResetEvent(false);
			var listenSocket = new Socket(
				AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			var serverSocket = new Socket(
					AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			Socket acceptedSocket = null;
			Exception ex = null;
			ThreadPool.QueueUserWorkItem(_ =>
			{
				SocketAsyncEventArgs asyncEventArgs;
				try {
					listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
					listenSocket.Listen(1);

					asyncEventArgs = new SocketAsyncEventArgs {AcceptSocket = serverSocket};
					asyncEventArgs.Completed += (s, e) =>
					{
						acceptedSocket = e.AcceptSocket;
						mainEvent.Set();
					};

				} catch (Exception e) {
					ex = e;
					return;
				} finally {
					readyEvent.Set();
				}

				try {
					if (listenSocket.AcceptAsync(asyncEventArgs))
						return;
					acceptedSocket = asyncEventArgs.AcceptSocket;
					mainEvent.Set();
				} catch (Exception e) {
					ex = e;
				}
			});
			Assert.IsTrue(readyEvent.WaitOne(1500));
			if (ex != null)
				throw ex;

			var clientSocket = new Socket(
				AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			clientSocket.Connect(listenSocket.LocalEndPoint);
			clientSocket.NoDelay = true;

			Assert.IsTrue(mainEvent.WaitOne(1500));
			Assert.AreEqual(serverSocket, acceptedSocket, "x");
			mainEvent.Reset();

			if (acceptedSocket != null)
				acceptedSocket.Close();

			listenSocket.Close();
			readyEvent.Close();
			mainEvent.Close();
		}
        public static void StartListening(int port = 11001)
        {
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = IPAddress.Parse(LocalSettings.ServerIP);
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
            _allDone = new ManualResetEvent(false);
            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,
                                         SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);
                while (true)
                {
                    // Set the event to nonsignaled state.
                    _allDone.Reset();
                    // Start an asynchronous socket to listen for connections.
                    listener.BeginAccept(
                        AcceptCallback,
                        listener);
                    // Wait until a connection is made before continuing.
                    _allDone.WaitOne();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();
        }
Example #35
0
        /// <summary>
        /// Runs a MethodInvoker delegate on the UI thread from whichever thread we are currently calling from and BLOCKS until it is complete
        /// </summary>
        /// <param name="ivk"></param>
        public void UIBlockingInvoke(MethodInvoker ivk)
        {
            System.Threading.ManualResetEvent UIAsyncComplete = new System.Threading.ManualResetEvent(false);
            UIAsyncComplete.Reset();
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(delegate()
                {
                    try
                    {
                        ivk();
                    }
                    finally
                    {
                        UIAsyncComplete.Set();
                    }
                }));

                UIAsyncComplete.WaitOne();
            }
            else
            {
                ivk();
            }
        }
        public bool UnInitialize()
        {
            lock (this)
            {
                lock (Clients)
                {
                    Clients.Remove(this);
                }


                if (_proxyServerInterface != null)
                {
                    ((IChannel)_proxyServerInterface).Opened  -= new EventHandler(MessageContainerTransportClient_Opened);
                    ((IChannel)_proxyServerInterface).Opening -= new EventHandler(MessageContainerTransportClient_Opening);
                    ((IChannel)_proxyServerInterface).Faulted -= new EventHandler(MessageContainerTransportClient_Faulted);
                    ((IChannel)_proxyServerInterface).Closing -= new EventHandler(MessageContainerTransportClient_Closing);

                    ((IChannel)_proxyServerInterface).Abort();
                    _proxyServerInterface = null;
                }

                if (_channelFactory != null)
                {
                    _channelFactory.Abort();
                    _channelFactory = null;
                }

                _connectingEvent.Reset();
            }

            return(true);
        }
Example #37
0
        public Dictionary <int, double> GetVariablesExperiment(string expName)
        {
            if (User != null)
            {
                _resetEvent.WaitOne();
                _resetEvent.Reset();
                try
                {
                    bool start = _server.RequestVariables(expName, CallbackAction, User.UserLever);

                    if (start)
                    {
                        _resetEvent.WaitOne();
                        _resetEvent.Set();
                    }
                    else
                    {
                        _resetEvent.Set();
                    }
                }
                catch
                {
                    _resetEvent.Set();
                }
                return(changed);
            }
            else
            {
                return(new Dictionary <int, double>());
            }
        }
        public void RunTest(bool useLowLatencyBackoffStrategy, int iterations)
        {
            var adapter = new BuiltinContainerAdapter();
            var messageHasBeenReceived = new ManualResetEvent(false);
            adapter.Handle<string>(s => messageHasBeenReceived.Set());

            ConfigureBus(adapter, useLowLatencyBackoffStrategy);

            var bus = adapter.Bus;

            var recordedLatencies = new List<TimeSpan>();

            iterations.Times(() =>
            {
                // let things calm down
                Console.Write("Calming down.... ");
                Thread.Sleep(30.Seconds());

                Console.Write("Sending! ");
                var sendTime = DateTime.UtcNow;
                bus.SendLocal("w0000tamafooook!!1");

                Console.Write("waiting... ");
                messageHasBeenReceived.WaitUntilSetOrDie(20.Seconds());

                var elapsedUntilNow = sendTime.ElapsedUntilNow();
                Console.WriteLine("got the message - recorded latency of {0}", elapsedUntilNow);
                recordedLatencies.Add(elapsedUntilNow);
                messageHasBeenReceived.Reset();
            });

            Console.WriteLine("AVERAGE RECORDED LATENCY: {0:0.00} s", recordedLatencies.Average(t => t.TotalSeconds));
        }
Example #39
0
        public void FilteringTargetWrapperAsyncTest2()
        {
            var myMockCondition = new MyMockCondition(false);
            var myTarget = new MyAsyncTarget();
            var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition);
            wrapper.Initialize(CommonCfg);
            var logEvent = new LogEventInfo();
            Exception lastException = null;
            var continuationHit = new ManualResetEvent(false);
            Action<Exception> continuation =
                ex =>
                {
                    lastException = ex;
                    continuationHit.Set();
                };

            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            continuationHit.WaitOne();
            Assert.IsNull(lastException);
            Assert.AreEqual(0, myTarget.WriteCount);
            Assert.AreEqual(1, myMockCondition.CallCount);

            continuationHit.Reset();
            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            continuationHit.WaitOne();
            Assert.IsNull(lastException);
            Assert.AreEqual(0, myTarget.WriteCount);
            Assert.AreEqual(2, myMockCondition.CallCount);
        }
Example #40
0
        public void SimpleCommunication()
        {
            var reset1 = new ManualResetEvent(false);
            var reset2 = new ManualResetEvent(false);

            INatterConnection connection2 = null;
            var connection1 =_client1.OnConnected(c => reset1.Set()).OnData((c, f) => HandleResponse(f, c)).Call(GetClient2Address());
            _client2.OnConnected(c => reset2.Set()).OnData((c, f) => { HandleResponse(f, c); connection2 = c; });
            Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect");
            Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect");

            reset1.Reset();
            reset2.Reset();
            _client1.OnDisconnected(c => reset1.Set());
            _client2.OnDisconnected(c => reset2.Set());
            Send(connection1, StartNumber);

            Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect");
            Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect");
            Assert.AreEqual(ConnectionState.Disconnected, connection1.State, "Client not disconnected");
            Assert.AreEqual(ConnectionState.Disconnected, connection2.State, "Client not disconnected");

            Assert.AreEqual(EndNumber, _lastResult, "Invalid last number");
            Assert.AreEqual((EndNumber - StartNumber) + 1, _count, "Invalid count");
        }
Example #41
0
        public void AsyncTargetWrapperAsyncTest1()
        {
            var myTarget = new MyAsyncTarget();
            var targetWrapper = new AsyncTargetWrapper(myTarget) { Name = "AsyncTargetWrapperAsyncTest1_Wrapper" };
            targetWrapper.Initialize(null);
            myTarget.Initialize(null);
            var logEvent = new LogEventInfo();
            Exception lastException = null;
            var continuationHit = new ManualResetEvent(false);
            AsyncContinuation continuation =
                ex =>
                {
                    lastException = ex;
                    continuationHit.Set();
                };

            targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            Assert.True(continuationHit.WaitOne());
            Assert.Null(lastException);
            Assert.Equal(1, myTarget.WriteCount);

            continuationHit.Reset();
            targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            continuationHit.WaitOne();
            Assert.Null(lastException);
            Assert.Equal(2, myTarget.WriteCount);
        }
Example #42
0
        public static void AppdomainLoop(bool benchConfiguration)
        {
            sync = new ManualResetEvent(false);
            while (true)
            {
                sync.Reset();
                // create appdomain
                logger.Debug("domain starting.");

                AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
                AppDomain Domain = AppDomain.CreateDomain("ApplicationKeeper", null, setup);
                //
                BrokerApplication app = (BrokerApplication)Domain.CreateInstanceAndUnwrap(
                    typeof(BrokerApplication).Assembly.FullName,
                    typeof(BrokerApplication).FullName);
                //RunAppInSeparateThread(app);
                app.Run(sync, benchConfiguration, true);
                // waitfor sync
                sync.WaitOne();

                // unload appdomain
                AppDomain.Unload(Domain);

                logger.Debug("domain unloaded.");

                GC.Collect(); // collects all unused memory
                GC.WaitForPendingFinalizers(); // wait until GC has finished its work
                GC.Collect();
            }
        }
        public void ClientCancelsLimitOrder()
        {
            OrderStatus status = OrderStatus.New;
            var manualResetEvent = new ManualResetEvent(false);

            var ib = new InteractiveBrokersBrokerage();
            ib.Connect();

            ib.OrderEvent += (sender, args) =>
            {
                status = args.Status;
                manualResetEvent.Set();
            };

            // try to sell a single share at a ridiculous price, we'll cancel this later
            var order = new Order("AAPL", SecurityType.Equity, -1, OrderType.Limit, DateTime.UtcNow, 100000);
            ib.PlaceOrder(order);
            manualResetEvent.WaitOne(2500);

            ib.CancelOrder(order);

            manualResetEvent.Reset();
            manualResetEvent.WaitOne(2500);

            Assert.AreEqual(OrderStatus.Canceled, status);
        }
Example #44
0
        public void Send(IcmpEchoSender.SendEchoInfo info, Action<IList<SendResult<IcmpEchoResponseDatagram>>> finished)
        {
            IPEndPoint endPoint = null;

            var finishedResult = new List<SendResult<IcmpEchoResponseDatagram>>();

            var senderImpl = new IcmpTracertSenderImpl();

            var lastTtl = 1;

            var manualResetevent = new ManualResetEvent(false);

            while (endPoint == null || endPoint.Address != info.IpAddress)
            {
                senderImpl.Send(new SendTracertInfo(info, lastTtl++),
                                result =>
                                    {
                                        endPoint = result.EndPoint as IPEndPoint;

                                        finishedResult.Add(result);

                                        manualResetevent.Set();
                                    });

                info.IncreaseSequence();

                manualResetevent.WaitOne();
                manualResetevent.Reset();
            }

            senderImpl.CloseHost();

            finished(finishedResult);
        }
Example #45
0
        public void AsyncTargetWrapperAsyncTest1()
        {
            var myTarget = new MyAsyncTarget();
            var targetWrapper = new AsyncTargetWrapper(myTarget);
            ((ISupportsInitialize)targetWrapper).Initialize();
            ((ISupportsInitialize)myTarget).Initialize();
            var logEvent = new LogEventInfo();
            Exception lastException = null;
            var continuationHit = new ManualResetEvent(false);
            AsyncContinuation continuation =
                ex =>
                {
                    lastException = ex;
                    continuationHit.Set();
                };

            targetWrapper.WriteLogEvent(logEvent, continuation);

            continuationHit.WaitOne();
            Assert.IsNull(lastException);
            Assert.AreEqual(1, myTarget.WriteCount);

            continuationHit.Reset();
            targetWrapper.WriteLogEvent(logEvent, continuation);
            continuationHit.WaitOne();
            Assert.IsNull(lastException);
            Assert.AreEqual(2, myTarget.WriteCount);
        }
Example #46
0
        public void TheadLocalTimeServerIsNotShared()
        {
            var ts1 = new TestDateTimeServer(now: new DateTime(2011, 1, 1));
            var ts2 = new TestDateTimeServer(now: new DateTime(2012, 1, 1));

            var g1 = new ManualResetEvent(false);
            var g2 = new ManualResetEvent(false);

            DateTime? t1Date = null;

            var t1 = new Thread(() => {
                DateTimeServer.SetLocal(ts1);
                g1.WaitOne();
                t1Date = DateTimeServer.Now;
                g2.Set();
            });

            var t2 = new Thread(() =>
            {
                DateTimeServer.SetLocal(ts2);
                g2.Set();
                g1.WaitOne();
            });

            t1.Start();
            t2.Start();

            Assert.That(g2.WaitOne(20), Is.True);
            g2.Reset();
            g1.Set();
            Assert.That(g2.WaitOne(20), Is.True);

            Assert.That(t1Date, Is.Not.Null);
            Assert.That(t1Date, Is.EqualTo(ts1.Now));
        }
Example #47
0
 public void Reset()
 {
     mStatus     = -1;
     Error       = null;
     IsCompleted = false;
     Result      = null;
     mSpinWait.Reset();
     mResetEvent.Reset();
 }
Example #48
0
 private static void Main(string[] args)
 {
     Console.WriteLine("App started");
     Runner();
     Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] press Any key to pause");
     Console.ReadKey();
     ManualResetEvent.Reset();
     Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] press Any key to continue");
     Console.ReadKey();
     ManualResetEvent.Set();
     Console.ReadKey();
 }
Example #49
0
 public override bool pause(out string error)
 {
     error = null;
     if (_mre.Reset())
     {
         return(true);
     }
     else
     {
         error = "Could not reset mutex. pause failed";
         return(false);
     }
 }
Example #50
0
        /// <summary>
        /// Uninitialize the client from operation.
        /// </summary>
        /// <returns></returns>
        public bool UnInitialize()
        {
            lock (Clients)
            {
                Clients.Remove(this);
            }

            lock (this)
            {
                if (_proxyServerInterface != null)
                {
                    try
                    {
                        ((IChannel)_proxyServerInterface).Opened  -= new EventHandler(MessageContainerTransportClient_Opened);
                        ((IChannel)_proxyServerInterface).Opening -= new EventHandler(MessageContainerTransportClient_Opening);
                        ((IChannel)_proxyServerInterface).Faulted -= new EventHandler(MessageContainerTransportClient_Faulted);
                        ((IChannel)_proxyServerInterface).Closing -= new EventHandler(MessageContainerTransportClient_Closing);

                        ((IChannel)_proxyServerInterface).Abort();
                    }
                    catch (Exception ex)
                    {
                        SystemMonitor.OperationError(string.Empty, ex);
                    }
                    finally
                    {
                        _proxyServerInterface = null;
                    }
                }

                if (_channelFactory != null)
                {
                    try
                    {
                        _channelFactory.Abort();
                    }
                    catch (Exception ex)
                    {
                        SystemMonitor.OperationError(string.Empty, ex);
                    }
                    finally
                    {
                        _channelFactory = null;
                    }
                }

                _connectingEvent.Reset();
            }

            return(true);
        }
Example #51
0
        // send thread function
        private void SendThread()
        {
            CSLogger.LogDebug("Enter SendThread");
            try
            {
                Message msg = null;
                while (true)
                {
                    if (m_socket == null || m_socket.Connected == false)
                    {
                        m_send_thread = null;
                        break;
                    }
                    m_event_wait_send.WaitOne();
                    m_event_wait_send.Reset();

                    lock (m_send_queue)
                    {
                        while (m_send_queue.Count > 0)
                        {
                            msg = m_send_queue.Peek();
                            byte[] bytes     = msg.ToBytes();
                            int    result    = 0;
                            int    byte_size = bytes.Length;
                            while (result != byte_size)
                            {
                                try
                                {
                                    result += m_socket.Send(bytes, result, byte_size - result, SocketFlags.None);
                                }
                                catch (System.Exception ex)
                                {
                                    CSLogger.LogError(ex.ToString());
                                }
                            }
                            m_send_queue.Dequeue();
                        }
                    }
                    System.Threading.Thread.Sleep(10);
                }
            }
            catch (SocketException /*e*/)
            {
                CSLogger.LogDebug("SendThread: SocketException ");
            }
            catch (Exception /*e*/)
            {
                CSLogger.LogDebug("SendThread: Exception ");
            }
            CSLogger.LogDebug("Exit SendThread");
        }
Example #52
0
 /// <summary>
 /// pauses the encoding process
 /// </summary>
 /// <param name="error">output for any errors that might ocurr during this method</param>
 /// <returns>true if encoding has been successfully paused, false if not</returns>
 public bool pause(out string error)
 {
     error = "";
     try
     {
         mre.Reset();
     }
     catch (Exception e)
     {
         error = e.Message;
         return(false);
     }
     return(true);
 }
        /// <summary>
        /// Signal the graph update thread to start processing graph updates if there are any in the <see cref="graphUpdateQueueAsync"/> queue.
        /// Returns: True if the other thread was signaled.
        /// </summary>
        private bool StartAsyncUpdatesIfQueued()
        {
            if (graphUpdateQueueAsync.Count > 0)
            {
#if UNITY_WEBGL
                throw new System.Exception("This should not happen in WebGL");
#else
                asyncGraphUpdatesComplete.Reset();
                graphUpdateAsyncEvent.Set();
                return(true);
#endif
            }
            return(false);
        }
Example #54
0
        private void SendThread()
        {
            try
            {
                while (true)
                {
                    if (!Connected)
                    {
                        _sendThread = null;
                        break;
                    }
                    _waitSend.WaitOne(); //阻塞当前线程
                    _waitSend.Reset();   //线程只处理一次,立即阻塞

                    lock (_sendQueue)
                    {
                        while (_sendQueue.Count > 0)
                        {
                            _sendProtocolItem = _sendQueue.Peek();
                            _bytes            = _sendProtocolItem.ProtocolItemBytes;
#if blowfish
                            _mbw.Clear();
                            _bytes = _encryptBF.Encrypt_ECB(_bytes);
                            _mbw.Write(_bytes.Length + ProtocolConf.PACKGE_LEN);
                            _mbw.Write(_bytes);
                            _bytes = _mbw.ToArray();
#endif
                            int result   = 0;
                            int byteSize = _bytes.Length;
                            while (result != byteSize)
                            {
                                result += _socket.Send(_bytes, result, byteSize - result, SocketFlags.None);
                            }
                            _sendQueue.Dequeue();

                            Debugger.Log("给服务器发送数据:" + result + ",    协议体:" + _sendProtocolItem.ToString());
                        }
                    }
                }
            }
            catch (SocketException se)
            {
                Debugger.LogError("MSocketException" + se);
            }
            catch (Exception e)
            {
                Debugger.LogError("MSocketException" + e);
            }
        }
Example #55
0
        public void Test()
        {
            CodeTimer.Time("ManualRestEvent(false)", () =>//无信号,可以通过WaitOne 阻塞线程的执行,通过Set发出信号唤醒等待的线程
            {
                using (System.Threading.ManualResetEvent are = new System.Threading.ManualResetEvent(false))
                {
                    System.Threading.ThreadPool.QueueUserWorkItem((s) =>
                    {
                        Thread.Sleep(2000);
                        Console.WriteLine("Run!");
                        are.Set();
                    });
                    Console.WriteLine(are.WaitOne(5000));
                }
            });

            CodeTimer.Time("ManualRestEvent(true)", () =>//有信号表示终止状态,即线程属于闲置状态
            {
                using (System.Threading.ManualResetEvent are = new System.Threading.ManualResetEvent(true))
                {
                    System.Threading.ThreadPool.QueueUserWorkItem((s) =>
                    {
                        Thread.Sleep(1000);
                        Console.WriteLine("Not Run!");
                        if (!are.SafeWaitHandle.IsClosed)
                        {
                            are.Set();
                        }
                    });
                    are.WaitOne();//不会等待子线程的结束
                }
            });

            CodeTimer.Time("ManualRestEvent(reset)", () =>
            {
                using (System.Threading.ManualResetEvent are = new System.Threading.ManualResetEvent(true))
                {
                    System.Threading.ThreadPool.QueueUserWorkItem((s) =>
                    {
                        Thread.Sleep(1000);
                        Console.WriteLine("Run!");
                        are.Set();
                    });
                    are.WaitOne(); //不会等待子线程的结束
                    are.Reset();   //
                    are.WaitOne();
                }
            });
        }
Example #56
0
        public bool Execute(string filename, string arg)
        {
            if (filename == null || filename.Length < 1)
            {
                //GCError.SetLastError("Invalid arugment(s).");
                return(false);
            }

            //try
            //{
            ProcessStartInfo pi = new ProcessStartInfo();

            pi.FileName       = filename;
            pi.CreateNoWindow = false;
            pi.Arguments      = " >> " + filename + ".log";

            waitEvent.Reset();

            Process p = Process.Start(pi);

            if (p != null)
            {
                p.Exited += new EventHandler(process_Exited);
                p.EnableRaisingEvents = true;
            }
            else
            {
                //GCError.SetLastError("Cannot start process." + filename);
                return(false);
            }

            bool res = waitEvent.WaitOne(TimeOut, true);

            if (!res)
            {
                //GCError.SetLastError("Execure script time out." + filename);
            }

            return(res);
            //}
            //catch (Exception err)
            //{
            //    //GCError.SetLastError("Start process failed." + filename);
            //    //GCError.SetLastError(err);
            //    return false;
            //}
        }
        public DebuggerEvent Wait()
        {
            for (int i = 0; i < 5; i++)
            {
                lock (queue.SyncRoot) {
                    if (queue.Count > 0)
                    {
                        return((DebuggerEvent)queue.Dequeue());
                    }

                    wait_event.Reset();
                }

                wait_event.WaitOne(3000, false);
            }

            return(null);
        }
 private void thread_entry()
 {
     for (;;)
     {
         try {
             main_loop();
             // Debug.Assert(update_sync_frame_ >= render_sync_frame_);
             while (update_sync_frame_ >= render_sync_frame_)
             {
                 manual_reset_event_.WaitOne();
                 manual_reset_event_.Reset();
             }
             ++update_sync_frame_;
         } catch (System.Exception e) {
             Debug.Log(e);
         }
     }
 }
Example #59
0
        /// <summary>
        /// 取出一个消息
        /// </summary>
        public Message PopData()
        {
            Message ci;

            mutex.WaitOne();
            if (cmdq.Count > 0)
            {
                ci = cmdq.Dequeue() as Message;
            }
            else
            {
                ci = null;
            }
            if (cmdq.Count == 0)
            {
                evt.Reset();
            }
            mutex.ReleaseMutex();
            return(ci);
        }
Example #60
0
        private void thread_entry()
        {
            // TaskManager.Instance.setCamera(camera);
            // restart();

            for (;;)
            {
                try {
                    main_loop();
                    while (update_sync_frame_ >= render_sync_frame_)
                    {
                        manual_reset_event_.WaitOne();
                        manual_reset_event_.Reset();
                    }
                    ++update_sync_frame_;
                } catch (System.Exception e) {
                    Debug.Log(e);
                }
            }
        }