Exemplo n.º 1
1
        public static void Main(string[] args)
        {

            var done = new EventWaitHandle(false, EventResetMode.AutoReset);

            var yield = new Thread(
                new ParameterizedThreadStart(
                    data =>
                    {
                        Console.WriteLine(new { data });

                        done.Set();
                    }
                )
            );

            Console.WriteLine("before wait " + DateTime.Now);

            // Additional information: Thread has not been started.
            done.WaitOne(2100);

            Console.WriteLine("after wait " + DateTime.Now);

            yield.Start(new { foo = "bar" });

            done.WaitOne();

            Console.WriteLine("done");

            CLRProgram.CLRMain();
        }
Exemplo n.º 2
0
        public static void Main()
        {
            // 1. 로그헬퍼 환경설정 읽기 - 클라이언트에서 xml파일로 환경설정 읽기
            LogHelper.XMLConfiguratorLoader.Loader("LogHelperXMLConfigure.txt");
            // 2. 프로그램 버전 설정
            LogHelper.XMLConfiguratorLoader.ProgramVersion = "1.0.0.0";

            // 3. 기본LogHelper를 등록 한다.
            LogHelper.LogHelper.AddLogHelper(LogHelperType.Default, "사용자 아이디");

            _ewh = new EventWaitHandle(false, EventResetMode.AutoReset);
            Console.WriteLine("동기화 처리된 스레드 시작");

            Thread T1 = new Thread(
                    new ThreadStart(ThreadProc1)
                );
            T1.Start();
            _ewh.WaitOne();

            Thread T2 = new Thread(
                    new ThreadStart(ThreadProc2)
                );
            T2.Start();
            _ewh.WaitOne();
            _ewh.Reset();
        }
Exemplo n.º 3
0
        public IEnumerable<int> First(EventWaitHandle wait)
        {
            wait.WaitOne();
            yield return 0;

            wait.WaitOne();
            yield return 1;
        }
Exemplo n.º 4
0
        public IEnumerable<int> Second(EventWaitHandle wait)
        {
            wait.WaitOne();
            yield return 5;

            wait.WaitOne();
            yield return 6;
        }
 public void ChangeCollection()
 {
   _handle = new EventWaitHandle(false, EventResetMode.ManualReset);
   var test = new ObservableDictionary<int, string>();
   test.Changed += Dictionary_Changed;
   test.Add(0, "myValue");
   Assert.IsTrue(_handle.WaitOne(10), "Add() is not recognized as a change");
   _handle.Reset();
   test[0] = "newValue";
   Assert.IsTrue(_handle.WaitOne(10), "this[] is not recognized as a change");
   _handle.Reset();
   test.Remove(0);
   Assert.IsTrue(_handle.WaitOne(10), "Remove() is not recognized as a change");
 }
Exemplo n.º 6
0
        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                long waketime = (long)e.Argument;

                using (SafeWaitHandle handle = CreateWaitableTimer(IntPtr.Zero, true, GetType().Assembly.GetName().Name + "Timer"))
                {
                    if (SetWaitableTimer(handle, ref waketime, 0, IntPtr.Zero, IntPtr.Zero, true))
                    {
                        using (EventWaitHandle wh = new EventWaitHandle(false,
                                                               EventResetMode.AutoReset))
                        {
                            wh.SafeWaitHandle = handle;
                            wh.WaitOne();
                        }
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error scheduling wake timer", ex);
            }
        }
        protected override IMove GetNextMove_Impl(IGameBoard board)
        {
            m_GameBoard = board as GameBoard;
            InkCollectorStrokeEventHandler handler = new InkCollectorStrokeEventHandler(m_InkPicture_Stroke);
            IMove move = null;

            m_Waiter = new EventWaitHandle(false, EventResetMode.ManualReset);
            m_InkPicture.Stroke += handler;

            try
            {
                while (move == null)
                {
                    m_Waiter.Reset();
                    if (m_Waiter.WaitOne())
                    {
                        move = m_Move;
                    }
                }
            }
            finally
            {
                m_InkPicture.Stroke -= handler;
            }

            return move;
        }
Exemplo n.º 8
0
 public DoubleLaunchLocker(string signalId, string waitId, bool force = false)
 {
     _force = force;
     SignalId = signalId;
     WaitId = waitId;
     bool isNew;
     _signalHandler = new EventWaitHandle(false, EventResetMode.AutoReset, signalId, out isNew);
     if (!isNew)
     {
         Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
         bool terminate = false;
         if (!force && !RequestConfirmation())
             terminate = true;
         if (!terminate)
         {
             _waitHandler = new EventWaitHandle(false, EventResetMode.AutoReset, waitId);
             if (_signalHandler.Set())
                 terminate = !_waitHandler.WaitOne(TIMEOUT);
             else
                 terminate = true;
         }
         if (terminate)
         {
             TryShutdown();
             ForceShutdown();
         }
         else
             Application.Current.ShutdownMode = ShutdownMode.OnLastWindowClose;
     }
     ThreadPool.QueueUserWorkItem(WaitingHandler, waitId);
 }
Exemplo n.º 9
0
 public void ServerResponds() {
   using (var container = SetupMefContainer()) {
     using (var server = container.GetExport<IServerProcessProxy>().Value) {
       var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
       var request = new IpcRequest {
         RequestId = 5,
         Protocol = IpcProtocols.Echo,
         Data = new IpcStringData {
           Text = "sdfsdsd"
         }
       };
       IpcResponse response = null;
       server.RunAsync(request, x => {
         response = x;
         waitHandle.Set();
       });
       Assert.IsTrue(waitHandle.WaitOne(TimeSpan.FromSeconds(5.0)), "Server did not respond within 5 seconds.");
       Assert.AreEqual(5, response.RequestId);
       Assert.AreEqual(IpcProtocols.Echo, response.Protocol);
       Assert.IsNotNull(request.Data);
       Assert.IsNotNull(response.Data);
       Assert.AreEqual(request.Data.GetType(), typeof(IpcStringData));
       Assert.AreEqual(response.Data.GetType(), typeof(IpcStringData));
       Assert.AreEqual((request.Data as IpcStringData).Text, (response.Data as IpcStringData).Text);
     }
   }
 }
Exemplo n.º 10
0
        public void CrashTestBeforeMerge()
        {
            string path = Path.GetFullPath ("TestData\\CrashTestBeforeMerge");
            using (var db = new KeyValueStore(path)) db.Truncate ();

            var doneSetting = new EventWaitHandle (false, EventResetMode.ManualReset, "CrashTestBeforeMerge");
            doneSetting.Reset ();

            string testPath = Path.Combine (Path.GetDirectoryName (Assembly.GetExecutingAssembly ().GetName ().CodeBase), "RazorTest.exe");
            var process = Process.Start (testPath, "CrashTestBeforeMerge");

            doneSetting.WaitOne (30000);
            if (!process.HasExited) {
                process.Kill ();
                process.WaitForExit ();
            }

            // Open the database created by the other program
            using (var db = new KeyValueStore(path)) {
                db.Manifest.Logger = (msg) => Console.WriteLine (msg);

                Console.WriteLine ("Begin enumeration.");
                ByteArray lastKey = new ByteArray ();
                int ct = 0;
                foreach (var pair in db.Enumerate()) {
                    ByteArray k = new ByteArray (pair.Key);
                    Assert.True (lastKey.CompareTo (k) < 0);
                    lastKey = k;
                    ct++;
                }
                Assert.AreEqual (10000, ct);
                Console.WriteLine ("Found {0} items in the crashed database.", ct);
            }
        }
Exemplo n.º 11
0
        public static SlackSocketClient GetClient(string authToken)
        {
            var wait = new EventWaitHandle(false, EventResetMode.ManualReset);

            var client = new SlackSocketClient(authToken);
            client.Connect(x =>
            {
                Console.WriteLine("RTM Start");
            }, () =>
            {
                Console.WriteLine("Connected");
                wait.Set();
            });

            Policy
                .Handle<AssertFailedException>()
                .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds))
                .Execute(() =>
                {
                    Assert.IsTrue(wait.WaitOne(), "Still waiting for things to happen...");
                });

            Policy
                .Handle<AssertFailedException>()
                .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds))
                .Execute(() =>
                {
                    Assert.IsTrue(client.IsConnected, "Doh, still isn't connected");
                });

            return client;
        }
Exemplo n.º 12
0
        /// <summary>
        /// Fetches the Tf2 Item schema.
        /// </summary>
        /// <param name="apiKey">The API key.</param>
        /// <returns>A  deserialized instance of the Item Schema.</returns>
        /// <remarks>
        /// The schema will be cached for future use if it is updated.
        /// </remarks>
        public static Schemazh FetchSchema()
        {
            var url = SchemaApiUrlBase;

            // just let one thread/proc do the initial check/possible update.
            bool wasCreated;
            var mre = new EventWaitHandle(false,
                EventResetMode.ManualReset, SchemaMutexName, out wasCreated);

            // the thread that create the wait handle will be the one to
            // write the cache file. The others will wait patiently.
            if (!wasCreated)
            {
                bool signaled = mre.WaitOne(10000);

                if (!signaled)
                {
                    return null;
                }
            }

            HttpWebResponse response = Drop.SteamWeb.Request(url, "GET");

            DateTime schemaLastModified = DateTime.Parse(response.Headers["Last-Modified"]);

            string result = GetSchemaString(response, schemaLastModified);

            response.Close();

            // were done here. let others read.
            mre.Set();

            SchemaResult schemaResult = JsonConvert.DeserializeObject<SchemaResult>(result);
            return schemaResult.result ?? null;
        }
Exemplo n.º 13
0
        public void ShouldJoinDirectMessageChannel()
        {
            // given
            var client = ClientHelper.GetClient(_config.Slack.UserAuthToken);

            string userName = _config.Slack.DirectMessageUser;
            string user = client.Users.First(x => x.name.Equals(userName, StringComparison.InvariantCultureIgnoreCase)).id;

            // when
            EventWaitHandle wait = new EventWaitHandle(false, EventResetMode.ManualReset);
            client.JoinDirectMessageChannel(response =>
            {
                Assert.IsTrue(response.ok, "Error while joining user channel");
                Assert.IsTrue(!string.IsNullOrEmpty(response.channel.id), "We expected a channel id to be returned");
                wait.Set();
            }, user);

            // then
            Policy
                .Handle<AssertFailedException>()
                .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds))
                .Execute(() =>
                {
                    Assert.IsTrue(wait.WaitOne(), "Took too long to do the THING");
                });
        }
Exemplo n.º 14
0
		public static void Sleep(int millisecondsTimeout)
		{
			using (var handle = new EventWaitHandle(false, EventResetMode.ManualReset))
			{
				handle.WaitOne(millisecondsTimeout);
			}
		}
        private static IList<Thread> CreateWorkers(EventWaitHandle ewh, Action action, int threadsNum, int cycles)
        {
            var threads = new Thread[threadsNum];

            for (int i = 0; i < threadsNum; i++)
            {
                Action d = () =>
                {
                    Console.WriteLine("Waiting");

                    // NOTE: all threads should wait here for a signal from the main thread.
                    ewh.WaitOne();
                    Console.WriteLine("Done");

                    for (int j = 0; j < cycles; j++)
                    {
                        action();
                    }
                };

                Thread thread = new Thread(new ThreadStart(d)); ; // TODO: Create a new thread that will run the delegate above here.
                threads[i] = thread;
            }

            return threads;
        }
Exemplo n.º 16
0
        void AuthSignIn()
        {
            EventWaitHandle wait = new EventWaitHandle(false, EventResetMode.ManualReset);
            SlackSocketClient client = new SlackSocketClient(token);
            client.OnHello += () =>
            {
                wait.Set();
            };
            client.Connect((l) =>
            {

                if (!l.ok) return;

                BeginInvoke(new Action(() =>
                {
                    connected = new ConnectedInterface(client, l);
                    connected.Dock = DockStyle.Fill;

                    Controls.Add(connected);

                    password.Visible = false;
                }));
            });
            wait.WaitOne();
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            // Create a IPC wait handle with a unique identifier.
            bool createdNew;
            var waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "ImperatorWaitHandle", out createdNew);

            // If the handle was already there, inform the other process to exit itself.
            // Afterwards we'll also die.
            if (!createdNew)
            {
                Console.WriteLine("Found other Imperator process. Requesting stop...");
                waitHandle.Set();
                Console.WriteLine("Informer exited.");

                return;
            }

            Console.WriteLine("Initializing Container...");
            var container = new ContainerInitializer().Initialize();

            Console.WriteLine("Connecting to UI...");
            var hubClient = container.GetInstance<IHubClient>();
            hubClient.OpenConnection();
            Console.WriteLine("Connected");

            Console.WriteLine("Initializing Imperator...");
            var i = container.GetInstance<Imperator>();
            i.InitializeConfig();
            i.StartImperator();

            waitHandle.WaitOne();
            Console.WriteLine("Closing Imperator...");
        }
Exemplo n.º 18
0
        public void BasicTest_StartWaiters()
        {
            _count = 0;
            const int NumThreads = 10;
            CountDownLatch latch = new CountDownLatch(1);
            EventWaitHandle[] handles = new EventWaitHandle[NumThreads];

            for (int i=0; i<NumThreads; i++)
            {
                handles[i] = new EventWaitHandle(false, EventResetMode.ManualReset);

                Thread thr = new Thread(delegate(object x) { 
                    latch.Await();
                    Interlocked.Increment(ref _count);
                    ((EventWaitHandle)x).Set();
                });
                thr.Name = String.Format("Thread {0}",i);
                thr.Start(handles[i]);
            }
            EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);
            Thread thr1 = new Thread(delegate(object x)
            {
                Thread.Sleep(100);
                EventWaitHandle.WaitAll(handles);
                ((EventWaitHandle)x).Set();
            });
            thr1.SetApartmentState(ApartmentState.MTA);
            thr1.Start(handle);
            
            Thread.Sleep(100);
            Expect(_count,EqualTo(0));
            latch.CountDown();
            handle.WaitOne();
            Expect(_count,EqualTo(NumThreads));
        }
Exemplo n.º 19
0
        public void StartUp(int parentID)
        {
            WaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);

            RemotingConfiguration.Configure("arduino.launcher.config", false);

            bool quit = false;
            while (!quit)
            {
                if (WaitHandle.WaitOne(1000))
                {
                    //give time for remoting to complete.
                    Thread.Sleep(1000);
                    quit = true;
                }
                else
                {
                    if (parentID != 0)
                    {
                        var parentProc = Process.GetProcessById(parentID);
                        if (parentProc.HasExited)
                        {
                            quit = true;
                        }
                    }
                }
            }
        }
Exemplo n.º 20
0
        private static void CacheXgsMonitor()
        {
            bool rc;

            try
            {
                // Once up front
                UpdateVms();

                for ( ; ;)
                {
                    rc = evvms.WaitOne(CACHE_MONITOR_TIMEOUT, false);
                    if (rc) // if (signaled)
                    {
                        // RJP our version clears the list first
                        lock (vms)
                            vms.Clear();
                        UpdateVms();
                    }

                    if (Shutdown)
                    {
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                log.Debug("Exception reading vms directory from XenGuestAgent", e);
            }
        }
Exemplo n.º 21
0
        private static void alertUpdater()
        {
            try
            {
                bool signal;

                for (; ;)
                {
                    signal = evalerts.WaitOne(2000, false);
                    if (signal) // if (signaled)
                    {
                        GetAlertCode();
                    }

                    if (Shutdown)
                    {
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                log.Debug("Exception retrieving alerts from XenGuestAgent", e);
            }
        }
Exemplo n.º 22
0
        static void RunInThreadPoolWithEvents()
        {
            double result = 0d;

            // We use this event to signal when the thread is don executing.
            EventWaitHandle calculationDone = new EventWaitHandle(false, EventResetMode.AutoReset);

            // Create a work item to read from I/O
            ThreadPool.QueueUserWorkItem((x) => {
                result += Utils.CommonFunctions.ReadDataFromIO();
                calculationDone.Set();
            });

            // Save the result of the calculation into another variable
            double result2 = Utils.CommonFunctions.DoIntensiveCalculations();

            // Wait for the thread to finish
            calculationDone.WaitOne();

            // Calculate the end result
            result += result2;

            // Print the result
            Console.WriteLine("The result is {0}", result);
        }
Exemplo n.º 23
0
    public bool ForceOnce()
    {
      Process process = Process.GetProcessById(_processId);
      if (process == null || process.HasExited)
        throw new InvalidOperationException("Cannot force focus, process is not running");

      _waitHandle = new AutoResetEvent(false);

      try
      {
        Win32.EnumWindowsProc ewc = CheckWindow;

        int focusedId = Win32.GetForegroundWindowPID();
        if (focusedId != _processId)
        {
          _windowHandle = IntPtr.Zero;
          Win32.EnumerateWindows(ewc, IntPtr.Zero);

          bool waitResult = _waitHandle.WaitOne(5000, false);
          if (waitResult && _windowHandle != IntPtr.Zero)
            return Win32.SetForegroundWindow(_windowHandle, true);
        }
      }
      finally
      {
        _waitHandle.Close();
        _waitHandle = null;
      }

      return false;
    }
Exemplo n.º 24
0
        public void Should_be_able_to_cancel_message_reception_upon_disposal()
        {
            const string mmfName = "Local\\test";
            var message = "not null";
            var messageCancelled = new EventWaitHandle(false, EventResetMode.ManualReset, mmfName + "_MessageCancelled");

            messageCancelled.Set();

            var messageReceiver = new MemoryMappedFileMessageReceiver(mmfName);

            var task = new Task(() => message = messageReceiver.ReceiveMessage(ReadString));

            task.Start();

            var isSet = true;

            while (isSet)
                isSet = messageCancelled.WaitOne(0);

            messageReceiver.Dispose();

            task.Wait();

            message.ShouldBeNull();
        }
Exemplo n.º 25
0
 public static void DisposeTimer(Timer timer)
 {
     Check.Require(timer, "timer");
     var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
     timer.Dispose(waitHandle);
     waitHandle.WaitOne(1000);
 }
Exemplo n.º 26
0
        public void LoadUserData(IList <Uri> addresses, bool IsTruncateTempDB = true)
        {
            WebHttpCrawlerClient client = new WebHttpCrawlerClient();

            client.SetRequestDetail = (x) =>
            {
                x._HttpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
                x._HttpWebRequest.Referer = "https://api.stackexchange.com/docs/users";
            };

            WebThreadDesigation t = new WebThreadDesigation(client);

            t.EventWaitHandleName = "WebThreadDesigation";

            StackoverflowPageAnalysis           ana = new StackoverflowPageAnalysis();
            AnalysisThreadDesigation <UserInfo> a   = new AnalysisThreadDesigation <UserInfo>(ana);

            a.EventWaitHandleName = "StackoverflowPageAnalysis";
            DBThreadDesigation d = new DBThreadDesigation();

            d.EventWaitHandleName = "DBThreadDesigation";
            CrawlerSyncObject  syscobject       = new CrawlerSyncObject();
            AnalysisSyncObject anasissyncObject = new AnalysisSyncObject();

            SendImformation infos = new SendImformation();

            infos.ConnectString = "data source=CIA-SH-svr-sis;initial catalog=stackoverflowNew;integrated security=True;";
            //infos.EventhandlerName = "dbo.SuggestionStagging";
            //infos.DestinationtableName = "dbo.SuggestionStagging";

            infos.EventhandlerName     = "UserTemp1_Tinct";
            infos.DestinationtableName = "UserTemp1_Tinct";
            infos.IsWantToMerged       = false;
            infos.MergeSQlSPName       = "";

            EventWaitHandle eventWaitHandle1 = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, t.EventWaitHandleName);

            eventWaitHandle1.Reset();
            EventWaitHandle eventWaitHandle2 = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, a.EventWaitHandleName);

            eventWaitHandle2.Reset();
            EventWaitHandle eventWaitHandle3 = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, d.EventWaitHandleName);

            eventWaitHandle3.Reset();
            EventWaitHandle eventWaitHandle4 = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, infos.EventhandlerName);

            eventWaitHandle4.Reset();
            Task.Run(() => { t.CrawlerUris(addresses, 10, syscobject); });
            Task.Run(() => { a.AnalysisResults(t.resultlists, 5, syscobject, anasissyncObject); });
            Task.Run(() =>
            {
                d.SendDispatchDatas <UserInfo>(ref a.datas, 500, ref anasissyncObject, infos,
                                               null);
            });
            eventWaitHandle1.WaitOne();
            eventWaitHandle2.WaitOne();
            eventWaitHandle3.WaitOne();
            eventWaitHandle4.WaitOne();
        }
Exemplo n.º 27
0
 public void TestAsyncThrowException()
 {
     log.info("TestAsyncThrowException(");
     EventWaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
     internalTestThrowException(waitHandle);
     waitHandle.WaitOne();
     log.info(")TestAsyncThrowException");
 }
 public void AddItem()
 {
   _handle = new EventWaitHandle(false, EventResetMode.ManualReset);
   var test = new ObservableDictionary<int, string>();
   test.ItemAdded += Dictionary_ItemEvent;
   test.Add(0, "myValue");
   Assert.IsTrue(_handle.WaitOne(10));
 }
Exemplo n.º 29
0
        public void AsyncLookupCustomerSetsCustomerName()
        {
            string ruleSet = "Lookup";
              var actual = RuleBaseClassesRoot.NewEditableRoot(ruleSet);

              var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
              actual.ValidationComplete += (o, e) => waitHandle.Set();
              waitHandle.Reset();
              actual.CustomerId = 1;
              waitHandle.WaitOne();  // wait for async lookup to complete
              Assert.AreEqual("Rocky Lhotka", actual.Name);

              waitHandle.Reset();
              actual.CustomerId = 2;
              waitHandle.WaitOne();
              Assert.AreEqual("Customer_2", actual.Name);
        }
 public void EnqueueItem()
 {
   _handle = new EventWaitHandle(false, EventResetMode.ManualReset);
   var test = new ObservableQueue<string>();
   test.ItemEnqueued += Queue_ItemEnqueued;
   test.Enqueue("test");
   Assert.IsTrue(_handle.WaitOne(10));
 }
        public void TestReadWriteLock_NoWriteWhileReading()
        {
            // ReSharper disable AccessToModifiedClosure
            // ReSharper disable AccessToDisposedClosure
            // ReSharper disable ImplicitlyCapturedClosure
            using (var rwlock = new ReadWriteLock())
            {
                string value = "foo";

                const string expected = "foo";
                string actual = null;

                var ewh1 = new EventWaitHandle(false, EventResetMode.ManualReset);
                var ewh2 = new EventWaitHandle(false, EventResetMode.ManualReset);

                var task1 = Task.Factory.StartNew(() =>
                {
                    using (rwlock.EnterReadScope())
                    {
                        ewh1.Set();
                        Assert.False(ewh2.WaitOne(TimeSpan.FromMilliseconds(100)));
                        Thread.Sleep(100);

                        actual = value;
                    }
                    Assert.True(ewh2.WaitOne(TimeSpan.FromSeconds(5)));
                });

                var task2 = Task.Factory.StartNew(() =>
                {
                    Assert.True(ewh1.WaitOne(TimeSpan.FromSeconds(5)));
                    using (rwlock.EnterWriteScope())
                        value = "bar";
                    ewh2.Set();
                });

                Assert.True(task1.Wait(TimeSpan.FromSeconds(5)));
                Assert.True(task2.Wait(TimeSpan.FromSeconds(5)));

                Assert.AreEqual(expected, actual);
            }
            // ReSharper restore ImplicitlyCapturedClosure
            // ReSharper restore AccessToDisposedClosure
            // ReSharper restore AccessToModifiedClosure
        }
 public void RemoveItem()
 {
   _handle = new EventWaitHandle(false, EventResetMode.ManualReset);
   var test = new ObservableList<string>();
   test.Add("myValue");
   test.ItemRemoved += List_ItemEvent;
   test.Remove("myValue");
   Assert.IsTrue(_handle.WaitOne(10));
 }
 public void ChangeItem()
 {
   _handle = new EventWaitHandle(false, EventResetMode.ManualReset);
   var test = new ObservableList<string>();
   test.Add("myValue");
   test.ItemChanged += List_ItemEvent;
   test[test.IndexOf("myValue")] = "myNewValue";
   Assert.IsTrue(_handle.WaitOne(10));
 }
Exemplo n.º 34
0
 public void WriteWord()
 {
     waiter.WaitOne();
     writingStarted();
     Thread.Sleep(randValue(Library.Settings.Instance.OperationTime, 15));
     using (StreamWriter sr = new StreamWriter(Library.Settings.Instance.File, true)) {
         string word = Library.Settings.Instance.Title + ": " + DateTime.Now;
         sr.WriteLine(word);
     }
     waiter.Set();
     writingFinished();
 }
Exemplo n.º 35
0
 public int ReadPacket(byte[] buffer, CancellationToken cancellationToken)
 {
     do
     {
         if (this.queue.Count > 0)
         {
             var bytes = this.queue.Dequeue();
             Array.Copy(bytes, buffer, bytes.Length);
             return(bytes.Length);
         }
         ewh.WaitOne();
     } while (!cancellationToken.IsCancellationRequested);
     return(0);
 }
Exemplo n.º 36
0
        public void JoinUntilSuspendedByMainLoop()
        {
            bool wait = false;

            lock (forState)
            {
                if (this.internalState != ThreadState.Stopped)
                {
                    wait = true;
                }
            }
            if (wait)
            {
                wakeUp.WaitOne();
            }
        }
Exemplo n.º 37
0
    public Tuple <float, float> getOdometry()
    {
        updated = false;
        waitHandle.WaitOne();

        //float angleTurned = Vector3.SignedAngle(lastDirection, currentDirection, Vector3.up);
        float angleTurned       = lastDirection - currentDirection;
        float distanceTravelled = Vector3.Distance(lastPosition, currentPosition);

        //Debug.Log($"{lastDirection} - {currentDirection} = {angleTurned}");
        //Quaternion rotation = Quaternion.Euler(0, angleTurned, 0);
        //Vector3 estimatedDirection = rotation * lastDirection;
        //Debug.Log($"{lastDirection} -{angleTurned}-> {estimatedDirection} = {currentDirection}");
        //total += angleTurned;
        //Debug.Log(total);

        lastDirection = currentDirection;
        lastPosition  = currentPosition;

        return(Tuple.Create(distanceTravelled, angleTurned));
    }
Exemplo n.º 38
0
        private void WaitForOwnership()
        {
            if (owningProcess)
            {
                return;
            }

            if (!matlabProcess.RequestOwnership(this))
            {
                eventWaitHandle.WaitOne();
            }
            try
            {
                matlabApp = new WeakReference <object>(matlabProcess.GetProcess(this).MatLabInstance);
            }
            catch (COMException)
            {
                RestartProcess();
            }
            owningProcess = true;
        }
Exemplo n.º 39
0
        public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
        {
            CheckState();
            if (millisecondsTimeout < -1)
            {
                throw new ArgumentOutOfRangeException("millisecondsTimeout",
                                                      "millisecondsTimeout is a negative number other than -1");
            }

            Stopwatch sw = Stopwatch.StartNew();

            Func <bool> stopCondition = () => millisecondsTimeout >= 0 && sw.ElapsedMilliseconds > millisecondsTimeout;

            do
            {
                bool shouldWait;
                int  result;

                do
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    if (stopCondition())
                    {
                        return(false);
                    }

                    shouldWait = true;
                    result     = currCount;

                    if (result > 0)
                    {
                        shouldWait = false;
                    }
                    else
                    {
                        break;
                    }
                } while (Interlocked.CompareExchange(ref currCount, result - 1, result) != result);

                if (!shouldWait)
                {
                    if (result == 1)
                    {
                        handle.Reset();
                    }
                    break;
                }

                SpinWait wait = new SpinWait();

                while (Thread.VolatileRead(ref currCount) <= 0)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    if (stopCondition())
                    {
                        return(false);
                    }

                    if (wait.Count > spinCount)
                    {
                        int timeout = millisecondsTimeout < 0 ? deepSleepTime :
                                      Math.Min(Math.Max(millisecondsTimeout - (int)sw.ElapsedMilliseconds, 1), deepSleepTime);
                        handle.WaitOne(timeout);
                    }
                    else
                    {
                        wait.SpinOnce();
                    }
                }
            } while (true);

            return(true);
        }
Exemplo n.º 40
0
        static void Main(string[] args)
        {
            System.Configuration.Install.InstallContext _arg = new System.Configuration.Install.InstallContext(null, args);
            if (_arg.IsParameterTrue("debug"))
            {
                System.Console.WriteLine("Wait for debugger, press any key to continue...");
                System.Console.ReadKey();
            }
            // dump version
            logIt(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo.ToString());
            // dump args
            logIt(string.Format("called by arg: ({0})", args.Length));
            foreach (string s in args)
            {
                logIt(s);
            }


            IniFile ini          = new IniFile(Path.Combine(Environment.ExpandEnvironmentVariables(@"%APSTHOME%"), "config.ini"));
            String  sMaxcapacity = ini.GetString("battery", "read_ratio_reboot", "false");

            Util.IsMaxCapacity = String.Compare(sMaxcapacity, "true", true) == 0 || String.Compare(sMaxcapacity, "1", true) == 0;
            //Util.IsMaxCapacity = true;
            logIt($"config Maxcapacity = {sMaxcapacity}:{Util.IsMaxCapacity}");
            System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            if (_arg.IsParameterTrue("start-service"))
            {
                // start service
                Boolean bRun = false;
                try
                {
                    ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name);
                    ewait.Close();
                    logIt("Instance already started.");
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    bRun = true;
                }
                catch (Exception) { }
                if (bRun)
                {
                    try {
                        ewait = new EventWaitHandle(false, EventResetMode.ManualReset, IdeviceInfoSvcHost_Event_Name);
                        //Util.InitEnviroment();
                        ThreadPool.QueueUserWorkItem(new WaitCallback(Util.runMonitorExe), null);
                        using (ServiceHost host = new ServiceHost(typeof(Device)))
                        {
                            host.Open();
                            Console.WriteLine(@"go to http://localhost:1930/device to test");
                            Console.WriteLine(@"Press any key to terminate...");
                            while (!ewait.WaitOne(1000))
                            {
                                if (System.Console.KeyAvailable)
                                {
                                    ewait.Set();
                                }
                            }
                            host.Close();
                        }
                        Util.bExit = true;
                        Util.runMonitorExe("-kill-service");
                        ewait.Close();
                    } catch (Exception)
                    {
                        logIt("iTunes MobileDevice.Dll not found.************");
                    }
                    Util.bExit = true;
                    Util.runMonitorExe("-kill-service");
                    ewait.Close();
                }
            }
            else if (_arg.IsParameterTrue("kill-service"))
            {
                // stop service
                try
                {
                    ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name);
                    if (ewait != null)
                    {
                        ewait.Set();
                    }
                }
                catch (Exception) { }
            }
            else
            {
                System.Console.WriteLine("IdeviceInfoSvcHost.exe");
                System.Console.WriteLine("-start-service: to start the service");
                System.Console.WriteLine("-kill-service: to stop the service");
            }
        }
Exemplo n.º 41
0
 internal MercuryResponse WaitResponse()
 {
     _waitHandle.WaitOne();
     return(_reference);
 }
Exemplo n.º 42
0
        public byte[] ReadUSB()
        {
            // try reading a few times, in case we lose the connection brieflyl
            for (int tries = 0; tries < 3; ++tries)
            {
                // set up a non-blocking ("overlapped") read
                const int rptLen = 15;
                byte[]    buf    = new byte[rptLen];
                buf[0] = 0x00;
                EventWaitHandle ev = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
                ov.OffsetLow   = ov.OffsetHigh = 0;
                ov.EventHandle = ev.SafeWaitHandle.DangerousGetHandle();
                HIDImports.ReadFile(fp, buf, rptLen, IntPtr.Zero, ref ov);

                // Wait briefly for the read to complete.  But don't wait forever - we might
                // be talking to a device interface that doesn't provide the type of status
                // report we're looking for, in which case we don't want to get stuck waiting
                // for something that will never happen.  If this is indeed the controller
                // interface we're interested in, it will respond within a few milliseconds
                // with our status report.
                if (ev.WaitOne(100))
                {
                    // The read completed successfully!  Get the result.
                    UInt32 readLen;
                    if (HIDImports.GetOverlappedResult(fp, ref ov, out readLen, 0) == 0)
                    {
                        // The read failed.  Try re-opening the file handle in case we
                        // dropped the connection, then re-try the whole read.
                        TryReopenHandle();
                        continue;
                    }
                    else if (readLen != rptLen)
                    {
                        // The read length didn't match what we expected.  This might be
                        // a different device (not a Pinscape controller) or a different
                        // version that we don't know how to talk to.  In either case,
                        // return failure.
                        return(null);
                    }
                    else
                    {
                        // The read succeed and was the correct size.  Return the data.
                        return(buf);
                    }
                }
                else
                {
                    // The read timed out.  This must not be our control interface after
                    // all.  Cancel the read and try reopening the handle.
                    HIDImports.CancelIo(fp);
                    if (TryReopenHandle())
                    {
                        continue;
                    }
                    return(null);
                }
            }

            // don't retry more than a few times
            return(null);
        }
Exemplo n.º 43
0
Arquivo: updator.cs Projeto: fdsc/old
        private static string downloadUpdateNotSync(string dirName, string update, string name, string version, string[] args)
        {
            toUpdateLog("update\r\n\t" + update + "\r\n\t" + name + "\r\n\t" + stringArrayToLogString(args, "\t"));

            string url;
            string versionLV = "";

            int CountOfTryes = 0;

            do
            {
                if (stopEvent.WaitOne(15000))
                {
                    return("");
                }

                CountOfTryes++;
                options.OptionsHandler updatesInfo = getUpdatesInfo(update, name, versionLV, out url);

                if (updatesInfo == null)
                {
                    var msg = "Программа '" + Application.ExecutablePath + "' не смогла найти нужную версию обновления для " + name;
                    toUpdateLog(msg);

                    if (CountOfTryes > 3)
                    {
                        MessageBox.Show(msg, "updatorvs8.ru");
                        return("");
                    }

                    continue;
                }
                // полученная информация логируется в getUpdatesInfo непосредственно
                toUpdateLog("update from version " + version + ": info from url " + url /* + "\r\n\t" + updatesInfo.writeToString().Replace("\n", "\n\t")*/);

                if (!updatesInfo.contains("end"))
                {
                    var msg = "Программа '" + Application.ExecutablePath + "' не обнаружила в файле информации об обновлениях поля end: " + name;

                    toUpdateLog("Отсутствует поле end в файле описания обновления");

                    if (CountOfTryes > 3 || stopEvent.WaitOne(158000))
                    {
                        MessageBox.Show(msg, "updatorvs8.ru");
                        return("");
                    }

                    continue;
                }

                if (updatesInfo["name", ""] != name)
                {
                    var msg = "Программа '" + Application.ExecutablePath + "' не смогла найти обновление. \r\n" + String.Format("Загрузка по url '{0}' дала несовместимый тип программы: ожидаемый тип {1}, фактический тип {2}", url, name, updatesInfo["name"]);
                    toUpdateLog(msg);
                    MessageBox.Show(msg);
                    throw new Exception(String.Format("Загрузка по url '{0}' дала несовместимый тип программы: ожидаемый тип {1}, фактический тип {2}", url, name, updatesInfo["name"]));
                }

                if (
                    (updatesInfo["replace", true] && updatesInfo["version", ""] != version)
                    ||
                    (version.CompareTo(updatesInfo["version", ""]) < 0)
                    )
                {
                    toUpdateLog(String.Format(
                                    "to update replace/compare {0}/{1}", updatesInfo["replace", true], version.CompareTo(updatesInfo["version", ""])
                                    ));

                    var breakFlag = false;
                    var eversions = updatesInfo["eralyes", ""].Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var ev in eversions)
                    {
                        if (ev.Length > 0 &&
                            version.CompareTo(ev) < 0 &&
                            ev.CompareTo(getVersionFromDate(DateTime.Now.AddDays(1.0))) <= 0
                            )     // защита от неверно установленной версии
                        {
                            versionLV = ev;
                            breakFlag = true;
                            toUpdateLog(String.Format("version {0} will be updated to {1}/{2} via {3} for {4}", version, updatesInfo["version", ""], updatesInfo["replace", true], versionLV, name));
                            // File.AppendAllText("via.st", argsString); // логирование.via.st
                            break;
                        }
                    }

                    if (!breakFlag)
                    {
                        return(downloadUpdateFile(dirName, update, name, updatesInfo["version", ""], args));
                    }
                }
                else
                {
                    toUpdateLog(String.Format("version {0} must not be updated to version {1}/{2} for {3}", version, updatesInfo["version", ""], updatesInfo["replace", true], name));
                    return("");
                }
            }while (true);
        }
Exemplo n.º 44
0
 public DeviceInformation WaitForSelection()
 {
     _handle.WaitOne();
     return(SelectedDevice);
 }
Exemplo n.º 45
0
        static void Main(string[] args)
        {
            System.Configuration.Install.InstallContext _arg = new System.Configuration.Install.InstallContext(null, args);
            if (_arg.IsParameterTrue("debug"))
            {
                System.Console.WriteLine("Wait for debugger, press any key to continue...");
                System.Console.ReadKey();
            }
            // dump version
            logIt(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo.ToString());
            // dump args
            logIt(string.Format("called by arg: ({0})", args.Length));
            foreach (string s in args)
            {
                logIt(s);
            }

            System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            if (_arg.IsParameterTrue("start-service"))
            {
                // start service
                Boolean bFind = false;
                try
                {
                    ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name);
                    ewait.Close();
                    logIt("Instance already started.");
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    bFind = true;
                }
                catch (Exception) { }
                if (bFind)
                {
                    try
                    {
                        ewait = new EventWaitHandle(false, EventResetMode.ManualReset, IdeviceInfoSvcHost_Event_Name);
                        //Util.InitEnviroment();

                        new Thread(() =>
                        {
                            iDeviceClass.start();
                        }).Start();
                        Console.WriteLine(@"Press any key to terminate...");
                        while (!ewait.WaitOne(1000))
                        {
                            if (System.Console.KeyAvailable)
                            {
                                ewait.Set();
                            }
                        }
                        ewait.Close();
                        iDeviceClass.stop();
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            else if (_arg.IsParameterTrue("kill-service"))
            {
                // stop service
                try
                {
                    ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name);
                    if (ewait != null)
                    {
                        ewait.Set();
                    }
                }
                catch (Exception) { }
            }
            else
            {
                System.Console.WriteLine("MonitoriDevice.exe");
                System.Console.WriteLine("-start-service: to start the service");
                System.Console.WriteLine("-kill-service: to stop the service");
            }
        }
Exemplo n.º 46
0
        private static void ExecuteProgram(bool isStep)
        {
            isRunning = true;
            INSTRUCTION currInstr;

            while (isRunning)
            {
                currInstr = instrmem[ip];
                ip++;
                switch (currInstr.instr)
                {
                case "+0":
                    p0(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "+1":
                    p1(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "+2":
                    p2(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "+3":
                    p3(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "+4":
                    p4(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "+5":
                    p5(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "+6":
                    p6(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "+7":
                    p7(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "+8":
                    p8(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "+9":
                    p9(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "-0":
                    n0(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "-1":
                    n1(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "-2":
                    n2(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "-3":
                    n3(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "-4":
                    n4(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "-5":
                    n5(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "-6":
                    n6(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "-7":
                    n7(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "-8":
                    n8(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                case "-9":
                    n9(currInstr.op1, currInstr.op2, currInstr.op3);
                    break;

                default:
                    mainForm.PrintOutput("Missing end of program card (+9000000000)", false);
                    isRunning = false;
                    break;
                }

                if (isStep && isRunning)
                {
                    mainForm.UpdateIP(ip);
                    waitHandle.WaitOne();
                }
            }

            mainForm.UpdateIP(-1);
            isLoaded = false;
            mainForm.SetMenuItem("F6", false);
        }