Reset() public method

public Reset ( ) : bool
return bool
 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");
 }
        public override bool Execute()
        {
            try
            {
                syncEventName = new TaskItem(Guid.NewGuid().ToString());
                
                handle = new EventWaitHandle(false, EventResetMode.ManualReset, syncEventName.ItemSpec);
                handle.Reset();

                threadLock = GetLock(lockName);

                new Thread(new ThreadStart(AsyncExecute)).Start();

                while (m_AsyncThreadState == ThreadState.NOT_STARTED)
                {
                    Thread.Sleep(500);
                }
                
                return true;
            }
            catch (Exception e)
            {
                try
                {
                    Log.LogErrorFromException(e);
                }
                catch { }
                return false;
            }
        }
        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;
        }
Esempio n. 4
0
        public void CrashTestOnMerge()
        {
            string path = Path.GetFullPath ("TestData\\CrashTestOnMerge");
            using (var db = new KeyValueStore(path)) db.Truncate ();

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

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

            doneSetting.WaitOne (30000);
            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 (50000, ct);
                Console.WriteLine ("Found {0} items in the crashed database.", ct);
            }
        }
Esempio n. 5
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();
        }
Esempio n. 6
0
 public Controller(BlockingMediator mediator)
 {
     _signal = new AutoResetEvent(false);
     mediator.AddSignal(_signal);
     dynamic config = ConfigurationManager.GetSection("delays");
     var delays = new Dictionary<MessageType, int>();
     foreach (string name in config)
     {
         delays[Hearts.Utility.Enum.Parse<MessageType>(name)] =
             int.Parse(config[name]);
     }
     foreach (var type in Hearts.Utility.Enum.GetValues<MessageType>())
     {
         var key = type;
         mediator.Subscribe(type, ignore =>
             {
                 if (delays.ContainsKey(key))
                 {
                     Thread.Sleep(delays[key]);
                 }
                 _signal.Reset();
                 if (!IsBlocking)
                 {
                     ThreadPool.QueueUserWorkItem(_ => _signal.Set());
                 }
             });
     }
 }
Esempio n. 7
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();
        }
Esempio n. 8
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);
        }
Esempio n. 9
0
 /// <summary>
 /// 开始测试初始化
 /// </summary>
 /// <param name="type">测试类型</param>
 /// <param name="count">测试数量</param>
 internal static void Start(TestType type, int count)
 {
     LoopCount  = count;
     ErrorCount = 0;
     TestType   = type;
     WaitHandle.Reset();
     Time.Restart();
 }
Esempio n. 10
0
 /// <summary>
 /// 开始测试初始化
 /// </summary>
 /// <param name="type">测试类型</param>
 /// <param name="count">测试数量</param>
 internal static void Start(TestType type, int count)
 {
     if (type != TestType.ClientSynchronous)
     {
         mapPointer.Clear();
     }
     waitCount  = LoopCount = count;
     ErrorCount = 0;
     TestType   = type;
     WaitHandle.Reset();
     Time.Restart();
 }
Esempio n. 11
0
 /// <summary>
 /// 开始测试初始化
 /// </summary>
 /// <param name="type">测试类型</param>
 /// <param name="count">测试数量</param>
 internal static void Start(TestType type, int count)
 {
     if (type != TestType.ClientSynchronous)
     {
         AutoCSer.Memory.Clear(mapPointer.ULong, mapPointer.GetSize() >> 3);
     }
     waitCount  = LoopCount = count;
     ErrorCount = 0;
     TestType   = type;
     WaitHandle.Reset();
     Time.Restart();
 }
Esempio n. 12
0
        /// <summary>
        /// Waits on 'waitEvent' with a timeout
        /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
        /// </summary>
        private bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, TimeoutTracker timeout)
        {
#if DEBUG
            Debug.Assert(MyLockHeld);
#endif
            waitEvent.Reset();
            numWaiters++;
            _fNoWaiters = false;

            //Setting these bits will prevent new readers from getting in.
            if (_numWriteWaiters == 1)
            {
                SetWritersWaiting();
            }
            if (_numWriteUpgradeWaiters == 1)
            {
                SetUpgraderWaiting();
            }

            bool waitSuccessful = false;
            ExitMyLock();      // Do the wait outside of any lock

            try
            {
                waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
            }
            finally
            {
                EnterMyLock();
                --numWaiters;

                if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
                {
                    _fNoWaiters = true;
                }

                if (_numWriteWaiters == 0)
                {
                    ClearWritersWaiting();
                }
                if (_numWriteUpgradeWaiters == 0)
                {
                    ClearUpgraderWaiting();
                }

                if (!waitSuccessful)        // We may also be aboutto throw for some reason.  Exit myLock.
                {
                    ExitMyLock();
                }
            }
            return(waitSuccessful);
        }
        public void LoadQuestionsData(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/questions";
            };

            WebThreadDesigation t = new WebThreadDesigation(client);
            t.EventWaitHandleName = "WebThreadDesigation";

            StackoverflowPageAnalysis ana = new StackoverflowPageAnalysis();
            AnalysisThreadDesigation<QuestionInfo> a = new AnalysisThreadDesigation<QuestionInfo>(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 = "QuestionTemp1_Tinct";
            infos.DestinationtableName = "QuestionTemp1_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<QuestionInfo>(ref a.datas, 500, ref anasissyncObject, infos,
                    null);
            });
            eventWaitHandle1.WaitOne();
            eventWaitHandle2.WaitOne();
            eventWaitHandle3.WaitOne();
            eventWaitHandle4.WaitOne();
        }
        static void TryDo(Action action, int timeout)
        {
            var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

            {
                AsyncCallback callback = ar => waitHandle.Set();
                action.BeginInvoke(callback, null);

                if (!waitHandle.WaitOne(timeout))
                {
                    waitHandle.Reset();
                    throw new TimeoutException("Failed to complete in the timeout specified.");
                }
            }
        }
Esempio n. 15
0
 public void Reset()
 {
     _ready.Reset();
     _start.Reset();
     _start.Reset();
     for( int i=0; i < 100; i++ )
     {
         using (EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset, _signal + ".ready" + i))
         {
             if (handle.WaitOne(0, false))
                 handle.Reset();
             else
                 break;
         }
     }
 }
Esempio n. 16
0
        public void Learn()
        {
            ewh=new EventWaitHandle(false,EventResetMode.AutoReset);

            for (int i = 0; i <=4; i++)
            {
                Thread t=new Thread(new ParameterizedThreadStart(ThreadProc));
                t.Start(i);
            }

            while (Interlocked.Read(ref threadCount)<5)
            {
                Thread.Sleep(500);
            }

            while (Interlocked.Read(ref threadCount)>0)
            {
                Console.WriteLine("Press Enter to release a waiting thread.");
                Console.ReadLine();
                clearCount.Set();
                WaitHandle.SignalAndWait(ewh, clearCount);
                Console.WriteLine("loop again.");
            }
            Console.WriteLine();

            ewh=new EventWaitHandle(false,EventResetMode.ManualReset);

            for (int i = 0; i <=4; i++)
            {
                Thread t=new Thread(new ParameterizedThreadStart(ThreadProc));
                t.Start(i);
            }

            while (Interlocked.Read(ref threadCount)<5)
            {
                Thread.Sleep(500);
            }

            Console.WriteLine("Press ENTER to release the waiting threads");
            Console.ReadLine();
            ewh.Set();
            ewh.Reset();
            Console.WriteLine("Press ENTER to release the waiting threads");
            Console.ReadLine();
            ewh.Set();
        }
Esempio n. 17
0
        private bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
        {
            waitEvent.Reset();
            numWaiters++;
            this.fNoWaiters = false;
            if (this.numWriteWaiters == 1)
            {
                this.SetWritersWaiting();
            }
            if (this.numWriteUpgradeWaiters == 1)
            {
                this.SetUpgraderWaiting();
            }
            bool flag = false;

            this.ExitMyLock();
            try
            {
                flag = waitEvent.WaitOne(millisecondsTimeout);//, false);
            }
            finally
            {
                this.EnterMyLock();
                numWaiters--;
                if (((this.numWriteWaiters == 0) && (this.numWriteUpgradeWaiters == 0)) && ((this.numUpgradeWaiters == 0) && (this.numReadWaiters == 0)))
                {
                    this.fNoWaiters = true;
                }
                if (this.numWriteWaiters == 0)
                {
                    this.ClearWritersWaiting();
                }
                if (this.numWriteUpgradeWaiters == 0)
                {
                    this.ClearUpgraderWaiting();
                }
                if (!flag)
                {
                    this.ExitMyLock();
                }
            }
            return(flag);
        }
        static void Main(string[] args)
        {
            Server _server = null;
            Application _application = null;            
            Query _results;
            //InputAdapter Config 
                InputConfig _inputConfig = new InputConfig();


                string _stopSignalName = "TimeToStop";                
                EventWaitHandle _adapterStopSignal = new EventWaitHandle(false, EventResetMode.ManualReset, _stopSignalName);                

                try
                {

                    // Creating the server and application
                    _server = Server.Create("localhost");
                    _application = _server.CreateApplication("TwitterStream");                    
                    var input = CepStream<TweetsType>.Create("TwitterInputStream", typeof(InputFactory), _inputConfig, EventShape.Point);

                    var query1 = from s in input
                                 group s by s.HashTag into grp
                                 from win in grp.TumblingWindow(TimeSpan.FromSeconds(10), HoppingWindowOutputPolicy.ClipToWindowEnd)
                                 select new
                                 {
                                     HashTag = grp.Key,
                                     cnt = win.Count()
                                 };
                    _results = query1.ToQuery(_application, "TweetsCount", "Data Query2", typeof(TotalCountOutputFactory),
                                          _stopSignalName,
                                          EventShape.Point,
                                          StreamEventOrder.FullyOrdered);
                    _adapterStopSignal.Reset();                    
                    //Start the Query                
                    _results.Start();
                    //_results2.Start();                    
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                }
        }
Esempio n. 19
0
        private bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
        {
            waitEvent.Reset();
            numWaiters += 1u;
            bool flag = false;

            this.ExitMyLock();
            try
            {
                flag = waitEvent.WaitOne(millisecondsTimeout, false);
            }
            finally
            {
                this.EnterMyLock();
                numWaiters -= 1u;
                if (!flag)
                {
                    this.ExitMyLock();
                }
            }
            return(flag);
        }
Esempio n. 20
0
        /// <summary>
        /// Waits on 'waitEvent' with a timeout of 'millisceondsTimeout.
        /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
        /// </summary>
        bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
        {
            Debug.Assert(MyLockHeld);

            waitEvent.Reset();
            numWaiters++;

            bool waitSuccessful = false;

            // Do the wait outside of any lock
            ExitMyLock();
            try {
                waitSuccessful = waitEvent.WaitOne(millisecondsTimeout, false);
            } finally {
                EnterMyLock();
                --numWaiters;
                if (!waitSuccessful)
                {
                    ExitMyLock();
                }
            }
            return(waitSuccessful);
        }
Esempio n. 21
0
        public void PingPong(EventResetMode mode)
        {
            // Create names for the two events
            string outboundName = Guid.NewGuid().ToString("N");
            string inboundName = Guid.NewGuid().ToString("N");

            // Create the two events and the other process with which to synchronize
            using (var inbound = new EventWaitHandle(true, mode, inboundName))
            using (var outbound = new EventWaitHandle(false, mode, outboundName))
            using (var remote = RemoteInvoke(PingPong_OtherProcess, mode.ToString(), outboundName, inboundName))
            {
                // Repeatedly wait for one event and then set the other
                for (int i = 0; i < 10; i++)
                {
                    Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds));
                    if (mode == EventResetMode.ManualReset)
                    {
                        inbound.Reset();
                    }
                    outbound.Set();
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Waits on 'waitEvent' with a timeout of 'millisecondsTimeout.
        /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
        /// </summary>
        /// <param name="waitEvent">
        /// The wait Event.
        /// </param>
        /// <param name="numWaiters">
        /// The num Waiters.
        /// </param>
        /// <param name="millisecondsTimeout">
        /// The milliseconds Timeout.
        /// </param>
        private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
        {
            Debug.Assert(this.MyLockHeld);

            waitEvent.Reset();
            numWaiters++;

            bool waitSuccessful = false;

            this.ExitMyLock(); // Do the wait outside of any lock
            try
            {
#if !NETCF
                if (!waitEvent.WaitOne(millisecondsTimeout))
                {
                    throw new InvalidOperationException("ReaderWriterLock timeout expired");
                }
#else
                if (!waitEvent.WaitOne(millisecondsTimeout, false))
                {
                    throw new InvalidOperationException("ReaderWriterLock timeout expired");
                }
#endif

                waitSuccessful = true;
            }
            finally
            {
                this.EnterMyLock();
                --numWaiters;
                if (!waitSuccessful)
                {
                    // We are going to throw for some reason.  Exit myLock.
                    this.ExitMyLock();
                }
            }
        }
        static void Main(string[] args)
        {
            Server _server = null;
            Application _application = null;            
            Query _results, _results2;
            //InputAdapter Config 
                InputConfig _inputConfig = new InputConfig();


                string _stopSignalName = "TimeToStop";                
                EventWaitHandle _adapterStopSignal = new EventWaitHandle(false, EventResetMode.ManualReset, _stopSignalName);                

                try
                {

                    // Creating the server and application
                    _server = Server.Create("localhost");
                    _application = _server.CreateApplication("TwitterStream");                    
                    var input = CepStream<TweetsType>.Create("TwitterInputStream", typeof(InputFactory), _inputConfig, EventShape.Point);                    

                    var query1 = from e in input
                                 select new { text = e.Text, createdAt = e.CreatedAt, location=e.Location, lang=e.Lang, tweetid=e.TweetID, followercnt=e.FollowersCount, friendscnt=e.FriendsCount, hash = e.HashTag, userName = e.UserName, timeZone=e.TimeZone, lat = e.Latitude, lon = e.Longitude };

                    _results = query1.ToQuery(_application, "TweetsData", "Data Query", typeof(OutputFactory),
                                          _stopSignalName,
                                          EventShape.Point,
                                          StreamEventOrder.FullyOrdered);
                    _adapterStopSignal.Reset();                    
                    //Start the Query                
                    _results.Start();                    
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                }
        }
Esempio n. 24
0
        private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
        {
            waitEvent.Reset();
            numWaiters++;

            bool waitSuccessful = false;

            ExitMyLock();
            try {
                if (!waitEvent.WaitOne(millisecondsTimeout))
                {
                    throw new InvalidOperationException("ReaderWriterLock timeout expired");
                }
                waitSuccessful = true;
            }
            finally {
                EnterMyLock();
                --numWaiters;
                if (!waitSuccessful)
                {
                    ExitMyLock();
                }
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Waits on 'waitEvent' with a timeout of 'millisceondsTimeout.  
        /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
        /// </summary>
        private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
        {
            Debug.Assert(IsLockHeld);

            waitEvent.Reset();
            numWaiters++;

            bool waitSuccessful = false;
            ExitLock();      // Do the wait outside of any lock 
            try
            {
#if SILVERLIGHT
                if (!waitEvent.WaitOne(millisecondsTimeout))
                    throw new Exception("ReaderWriterLock timeout expired");
#else
                if (!waitEvent.WaitOne(millisecondsTimeout, false))
                    throw new Exception("ReaderWriterLock timeout expired");
#endif
                waitSuccessful = true;
            }
            finally
            {
                EnterLock();
                --numWaiters;
                if (!waitSuccessful)        // We are going to throw for some reason.  Exit myLock. 
                    ExitLock();
            }
        }
        private static void AddRemoveItems(ConcurrentQueue<Tuple<bool, IRoundRobinWorker>> addRemoveQueue, EventWaitHandle waitHandle, List<IRoundRobinWorker> workers)
        {
            waitHandle.Reset();

            Tuple<bool, IRoundRobinWorker> worker;
            while (addRemoveQueue.TryDequeue(out worker))
            {
                if (worker.Item1)
                {
                    // Add
                    workers.Add(worker.Item2);
                }
                else
                {
                    // Remove
                    int index = 0;
                    while (index < workers.Count)
                    {
                        if (workers[index].Token == worker.Item2.Token)
                        {
                            workers.RemoveAt(index);        // there should never be more than one, but just loop through them all to be sure
                        }
                        else
                        {
                            index++;
                        }
                    }
                }
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Waits on 'waitEvent' with a timeout  
        /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
        /// </summary>
        private bool WaitOnEvent(
            EventWaitHandle waitEvent,
            ref uint numWaiters,
            TimeoutTracker timeout,
            bool isWriteWaiter)
        {
#if DEBUG
            Debug.Assert(MyLockHeld);
#endif
            waitEvent.Reset();
            numWaiters++;
            _fNoWaiters = false;

            //Setting these bits will prevent new readers from getting in.
            if (_numWriteWaiters == 1)
                SetWritersWaiting();
            if (_numWriteUpgradeWaiters == 1)
                SetUpgraderWaiting();

            bool waitSuccessful = false;
            ExitMyLock();      // Do the wait outside of any lock

            try
            {
                waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
            }
            finally
            {
                EnterMyLock();
                --numWaiters;

                if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
                    _fNoWaiters = true;

                if (_numWriteWaiters == 0)
                    ClearWritersWaiting();
                if (_numWriteUpgradeWaiters == 0)
                    ClearUpgraderWaiting();

                if (!waitSuccessful)        // We may also be about to throw for some reason.  Exit myLock.
                {
                    if (isWriteWaiter && _numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && !_fNoWaiters)
                    {
                        // Write waiters block read waiters from acquiring the lock. Since this was the last write waiter and
                        // there is a read waiter, wake up the appropriate read waiters.
                        ExitAndWakeUpAppropriateReadWaiters();
                    }
                    else
                        ExitMyLock();
                }
            }
            return waitSuccessful;
        }
        //--------------------------------------------------------------------------
        // Data Reception
        //--------------------------------------------------------------------------

        // http://www.beefycode.com/post/Using-Overlapped-IO-from-Managed-Code.aspx

        #pragma warning disable 0618 // warning CS0618: 'System.Threading.WaitHandle.Handle' is obsolete: 'Use the SafeWaitHandle property instead.'

        unsafe void ReadThread(ThreadContext ctx)
            {
            System.Threading.Thread.CurrentThread.Name = "USBConnection.ReadThread";

            EventWaitHandle     asyncReadCompleteEvent = new EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);
            NativeOverlapped*   pNativeOverlapped      = null;
            byte[]              rgbBuffer              = new byte[64];

            try {
                WaitHandle[] waitHandles = new WaitHandle[2];
                waitHandles[0] = asyncReadCompleteEvent;
                waitHandles[1] = ctx.StopEvent;
                //
                // If we get unexpected errors, we stop reading; likely these are caused by a device
                // in the process of disconnecting.
                //
                bool fStop = false;
                //
                while (!fStop && !ctx.StopRequest)
                    {
                    // Issue an async read
                    // 
                    asyncReadCompleteEvent.Reset();
                    Overlapped overlapped = new Overlapped(0, 0, asyncReadCompleteEvent.Handle, null);
                    pNativeOverlapped = overlapped.Pack(null, rgbBuffer);
                    int cbRead = 0;

                    // Program.Trace("issuing async read: 0x{0:08X} 0x{1:08X}", new IntPtr(pNativeOverlappedWrite), this.hWinUSB);
                    bool fSuccess = WinUsb_ReadPipe(
                        this.hWinUSB,
                        bulkInPipe,
                        rgbBuffer,
                        rgbBuffer.Length,
                        out cbRead,
                        new IntPtr(pNativeOverlapped));

                    this.readThreadRunning.Set();

                    if (!fSuccess)
                        {
                        int err = Marshal.GetLastWin32Error();
                        if (err != ERROR_IO_PENDING)
                            {
                            Program.Trace("USB Read: WinUsb_ReadPipe=={0}", err);
                            fStop = true;
                            continue;
                            }
                        }

                    // Wait until either the async read completes or we're asked to stop
                    int iWait = WaitHandle.WaitAny(waitHandles);
                
                    // Process according to which event fired
                    switch (iWait)
                        {
                    case 0: // Async read completed
                        {
                        // Program.Trace("async read complete: 0x{0:08X} 0x{1:08X}", new IntPtr(pNativeOverlappedWrite), this.hWinUSB);
                        if (WinUsb_GetOverlappedResult(this.hWinUSB, new IntPtr(pNativeOverlapped), ref cbRead, System.Convert.ToByte(true)))
                            {
                            ProcessIncomingPacket(rgbBuffer, cbRead);
                            }
                        else
                            {
                            int err = Marshal.GetLastWin32Error();
                            Program.Trace("USB Read: WinUsb_GetOverlappedResult=={0}", err);
                            fStop = true;
                            }
                        //
                        System.Threading.Overlapped.Free(pNativeOverlapped);
                        pNativeOverlapped = null;
                        }
                        break;
                    case 1: // StopEvent 
                        // Program.Trace("async read stop requested");
                        break;
                    // end switch
                        }
                    }
                }
            finally 
                {
                // Program.Trace("async cleanup: 0x{0:08X} 0x{1:08X}", new IntPtr(pNativeOverlappedWrite), this.hWinUSB);
                WinUsb_AbortPipe(this.hWinUSB, bulkInPipe);
                asyncReadCompleteEvent.Close();

                if (pNativeOverlapped != null)
                    {
                    System.Threading.Overlapped.Free(pNativeOverlapped);
                    pNativeOverlapped = null;
                    }
                }
            }
        //--------------------------------------------------------------------------
        // Data reception
        //--------------------------------------------------------------------------

        unsafe void ReadThread(ThreadContext ctx)
            {
            System.Threading.Thread.CurrentThread.Name = "BluetoothConnection.ReadThread";

            EventWaitHandle     asyncReadCompleteEvent = new EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);
            NativeOverlapped*   pNativeOverlapped      = null;
            byte[]              rgbBuffer              = new byte[64];

            try {
                WaitHandle[] waitHandles = new WaitHandle[2];
                waitHandles[0] = asyncReadCompleteEvent;
                waitHandles[1] = ctx.StopEvent;
                //
                while (!ctx.StopRequest)
                    {
                    // Issue an async read
                    // 
                    asyncReadCompleteEvent.Reset();
                    Overlapped overlapped = new Overlapped(0, 0, asyncReadCompleteEvent.SafeWaitHandle.DangerousGetHandle(), null);
                    pNativeOverlapped = overlapped.Pack(null, rgbBuffer);
                    int cbRead = 0;

                    bool fSuccess = ReadFile(this.hSerialPort, rgbBuffer, rgbBuffer.Length, out cbRead, new IntPtr(pNativeOverlapped));
                    readThreadRunning.Set();
                    if (!fSuccess)
                        {
                        int err = Marshal.GetLastWin32Error();
                        if (err != ERROR_IO_PENDING)
                            ThrowWin32Error(err);
                        }

                    // Wait until either the async read completes or we're asked to stop
                    int iWait = WaitHandle.WaitAny(waitHandles);
                
                    // Process according to which event fired
                    switch (iWait)
                        {
                    case 0: // Async read completed
                        {
                        ThrowIfFail(GetOverlappedResult(this.hSerialPort, new IntPtr(pNativeOverlapped), ref cbRead, System.Convert.ToByte(true)));
                        // Program.Trace("async read complete: 0x{0:08X} 0x{1:08X} cb={2}", new IntPtr(pNativeOverlapped), this.hSerialPort, cbRead);

                        // Record the new data and process any packets that are now complete
                        this.RecordIncomingData(rgbBuffer, cbRead);
                        ProcessPacketIfPossible();

                        System.Threading.Overlapped.Free(pNativeOverlapped);
                        pNativeOverlapped = null;
                        }
                        break;
                    case 1: // StopEvent 
                        break;
                    // end switch
                        }

                    }
                }
            finally 
                {
                CancelIo(this.hSerialPort);
                asyncReadCompleteEvent.Close();

                if (pNativeOverlapped != null)
                    {
                    System.Threading.Overlapped.Free(pNativeOverlapped);
                    pNativeOverlapped = null;
                    }
                }
            }
Esempio n. 30
0
        /// <summary>
        /// Waits on 'waitEvent' with a timeout  
        /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
        /// </summary>
        private bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, TimeoutTracker timeout)
        {
#if DEBUG
            Debug.Assert(MyLockHeld);
#endif
            waitEvent.Reset();
            numWaiters++;
            fNoWaiters = false;

            //Setting these bits will prevent new readers from getting in.
            if (numWriteWaiters == 1)
                SetWritersWaiting();
            if (numWriteUpgradeWaiters == 1)
                SetUpgraderWaiting();            

            bool waitSuccessful = false;
            ExitMyLock();      // Do the wait outside of any lock

            try
            {
                waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
            }
            finally
            {
                EnterMyLock();
                --numWaiters;

                if (numWriteWaiters == 0 && numWriteUpgradeWaiters == 0 && numUpgradeWaiters == 0 && numReadWaiters == 0)
                    fNoWaiters = true;

                if (numWriteWaiters == 0)
                    ClearWritersWaiting();
                if (numWriteUpgradeWaiters == 0)
                    ClearUpgraderWaiting();
                
                if (!waitSuccessful)        // We may also be aboutto throw for some reason.  Exit myLock. 
                    ExitMyLock();
            }
            return waitSuccessful;
        }
Esempio n. 31
0
        public GpgInterfaceResult Execute()
        {
            GpgInterfaceResult result = null;

            try
            {
                lock (_alreadyUsedLock)
                {
                    if (_alreadyUsed)
                        throw new GpgInterfaceAlreadyUsed();
                    _alreadyUsed = true;
                }

                if (!File.Exists(GpgInterface.ExePath))
                    throw new FileNotFoundException(null, GpgInterface.ExePath);

                _outputEventWait = new ManualResetEvent(false);
                _abortedEventWait = new ManualResetEvent(false);
                _exitedEventWait = new ManualResetEvent(false);

                Log("Execute " + this);

                result = GpgInterfaceResult.Started;
                EmitEvent(result);

                result = BeforeStartProcess();
                if (result.Status != GpgInterfaceStatus.Success)
                {
                    EmitEvent(result);
                    return result;
                }

                _process = GetProcess(Arguments());
                _process.Exited += delegate(Object sender, EventArgs args)
                {
                    _processExited = true;
                    _exitedEventWait.Set();
                };
                _process.EnableRaisingEvents = true;

                _process.Start();
                _process.BeginErrorReadLine();

                _outputThread = new Thread(OutputReader) { Name = ToString() + " - OutputReader" };
                _outputThread.Start();

                while (WaitHandle.WaitAny(new WaitHandle[] { _outputEventWait, _abortedEventWait, _exitedEventWait }) != -1)
                {
                    if (_aborted)
                        break;

                    if (_processExited)
                    {
                        if (_outputThread != null)
                            _outputThread.Join();
                        _outputThread = null;
                    }

                    _outputEventWait.Reset();

                    GpgOutput output;
                    while (!_aborted && _output.TryDequeue(out output))
                    {
                        Log(output.Str);
                        result = ProcessLine(output.Str);

                        if (result.Status == GpgInterfaceStatus.Success)
                            continue;

                        EmitEvent(result);

                        if (result.Status == GpgInterfaceStatus.Error)
                        {
                            _aborted = true;
                            break;
                        }
                    }

                    if (_processExited && _outputThread == null)
                        break;
                }

                if (!_aborted)
                {
                    result = GpgInterfaceResult.Success;
                    EmitEvent(result);
                }
                else if (_aborted && result.Status != GpgInterfaceStatus.Error)
                {
                    result = GpgInterfaceResult.UserAbort;
                    EmitEvent(result);
                }

                Log("Exit");
            }
            catch (Exception e)
            {
                result = new GpgInterfaceResult(GpgInterfaceStatus.Error, GpgInterfaceMessage.None, e);
                EmitEvent(result);
            }
            finally
            {
                CleanUp();
            }

            return result;
        }
Esempio n. 32
0
        protected virtual void Start()
        {
            if (ProcessHelper.IsLocalMachine(this.MachineName))
            {
                if (process == null)
                {
                    waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, waitHandleName);
                    waitHandle.Reset();

                    ProcessStartInfo processStartInfo = new ProcessStartInfo();
                    processStartInfo.FileName = ExecutablePath;
                    
                    if (AstoriaTestProperties.RuntimeEnvironment == TestRuntimeEnvironment.CheckinSuites)
                    {
                        processStartInfo.CreateNoWindow = true;
                        processStartInfo.UseShellExecute = false;
                    }

                    if (AstoriaTestProperties.Host == Host.IDSH)
                        processStartInfo.Arguments = ServiceRootUri + " false" + " " + waitHandleName;
                    else if (AstoriaTestProperties.Host == Host.IDSH2)
                        processStartInfo.Arguments = ServiceRootUri + " true" + " " + waitHandleName;
                    else
                        processStartInfo.Arguments = ServiceRootUri + " " + waitHandleName;

                    process = Process.Start(processStartInfo);
                }
            }
        }
Esempio n. 33
0
        /// <summary>
        /// Waits on 'waitEvent' with a timeout of 'millisceondsTimeout.  
        /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
        /// </summary>
        bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
        {
            Debug.Assert (MyLockHeld);

            waitEvent.Reset ();
            numWaiters++;

            bool waitSuccessful = false;

            // Do the wait outside of any lock
            ExitMyLock();
            try {
                waitSuccessful = waitEvent.WaitOne (millisecondsTimeout, false);
            } finally {
                EnterMyLock ();
                --numWaiters;
                if (!waitSuccessful)
                    ExitMyLock ();
            }
            return waitSuccessful;
        }
Esempio n. 34
0
        public static void Start() {
            if (_listenTask == null) {
                lock (typeof (Monitor)) {
                    _cancellationTokenSource = new CancellationTokenSource();

                    bool wasCreated;
                    var ewhSec = new EventWaitHandleSecurity();
                    ewhSec.AddAccessRule(
                        new EventWaitHandleAccessRule(
                            new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    var sessionAckEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_BUFFER_READY", out wasCreated, ewhSec);
                    var sessionReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_DATA_READY", out wasCreated, ewhSec);
                    var globalAckEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Global\\DBWIN_BUFFER_READY", out wasCreated, ewhSec);
                    var globalReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Global\\DBWIN_DATA_READY", out wasCreated, ewhSec);

                    var sd = new SECURITY_DESCRIPTOR();
                    var sa = new SECURITY_ATTRIBUTES();

                    // Initialize the security descriptor.
                    if (!Advapi32.InitializeSecurityDescriptor(ref sd, 1)) {
                        throw new ApplicationException(
                            string.Format("{0}. Last Win32 Error was {1}", "Failed to initializes the security descriptor.", Marshal.GetLastWin32Error()));
                    }

                    // Set information in a discretionary access control list
                    if (!Advapi32.SetSecurityDescriptorDacl(ref sd, true, IntPtr.Zero, false)) {
                        throw new ApplicationException(
                            string.Format("{0}. Last Win32 Error was {1}", "Failed to initializes the security descriptor", Marshal.GetLastWin32Error()));
                    }

                    // Create the event for slot 'DBWIN_BUFFER_READY'
                    sa.nLength = Marshal.SizeOf(sa);
                    sa.lpSecurityDescriptor = Marshal.AllocHGlobal(Marshal.SizeOf(sd));
                    Marshal.StructureToPtr(sd, sa.lpSecurityDescriptor, false);

                    // Get a handle to the readable shared memory at slot 'DBWIN_BUFFER'.
                    var sessionSharedFileHandle = Kernel32.CreateFileMapping(new IntPtr(-1), ref sa, PageProtection.ReadWrite, 0, 4096, "DBWIN_BUFFER");
                    if (sessionSharedFileHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a file mapping to slot 'DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    // Create a view for this file mapping so we can access it
                    var sessionSharedMemoryHandle = Kernel32.MapViewOfFile(sessionSharedFileHandle, /*SECTION_MAP_READ*/ 0x0004, 0, 0, 4096);
                    if (sessionSharedMemoryHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a mapping view for slot 'DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    // Get a handle to the readable shared memory at slot 'DBWIN_BUFFER'.
                    var globalSharedFileHandle = Kernel32.CreateFileMapping(new IntPtr(-1), ref sa, PageProtection.ReadWrite, 0, 4096, "Global\\DBWIN_BUFFER");
                    if (globalSharedFileHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a file mapping to slot 'Global\\DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    // Create a view for this file mapping so we can access it
                    var globalSharedMemoryHandle = Kernel32.MapViewOfFile(globalSharedFileHandle, /*SECTION_MAP_READ*/ 0x0004, 0, 0, 4096);
                    if (globalSharedMemoryHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a mapping view for slot 'Global\\DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    var queue = new Queue<Tuple<int, DateTime, string>>();
                    var dataAvailable = new ManualResetEvent(true);

                    _listenTask = Task.Factory.StartNew(
                        () => {
                            // Everything after the first DWORD is our debugging text
                            IntPtr sessionStringPointer;
                            IntPtr globalStringPointer;

                            if (Environment.Is64BitProcess) {
                                sessionStringPointer = new IntPtr(sessionSharedMemoryHandle.ToInt64() + Marshal.SizeOf(typeof (int)));
                                globalStringPointer = new IntPtr(globalSharedMemoryHandle.ToInt64() + Marshal.SizeOf(typeof (int)));
                            } else {
                                sessionStringPointer = new IntPtr(sessionSharedMemoryHandle.ToInt32() + Marshal.SizeOf(typeof (int)));
                                globalStringPointer = new IntPtr(globalSharedMemoryHandle.ToInt32() + Marshal.SizeOf(typeof (int)));
                            }

                            while (!_cancellationTokenSource.IsCancellationRequested) {
                                sessionAckEvent.Set();
                                globalAckEvent.Set();

                                try {
                                    var i = WaitHandle.WaitAny(new[] {
                                        sessionReadyEvent, globalReadyEvent, _cancellationTokenSource.Token.WaitHandle
                                    });
                                    var now = DateTime.Now;
                                    if (i == 0) {
                                        lock (queue) {
                                            queue.Enqueue(new Tuple<int, DateTime, string>(Marshal.ReadInt32(sessionSharedMemoryHandle), now, Marshal.PtrToStringAnsi(sessionStringPointer)));
                                            dataAvailable.Set();
                                        }
                                    }

                                    if (i == 1) {
                                        lock (queue) {
                                            queue.Enqueue(new Tuple<int, DateTime, string>(Marshal.ReadInt32(globalSharedMemoryHandle), now, Marshal.PtrToStringAnsi(globalStringPointer)));
                                            dataAvailable.Set();
                                        }
                                    }
                                } catch {
                                    // it's over. 
                                    _cancellationTokenSource.Cancel();
                                }
                            }
                            _listenTask = null;

                            // cleanup after stopping.
                            globalAckEvent.Reset();
                            globalAckEvent.Dispose();
                            globalAckEvent = null;

                            sessionAckEvent.Reset();
                            sessionAckEvent.Dispose();
                            sessionAckEvent = null;

                            globalReadyEvent.Reset();
                            globalReadyEvent.Dispose();
                            globalReadyEvent = null;

                            sessionReadyEvent.Reset();
                            sessionReadyEvent.Dispose();
                            sessionReadyEvent = null;

                            // Close SharedFile
                            if (sessionSharedFileHandle != IntPtr.Zero) {
                                if (!Kernel32.CloseHandle(sessionSharedFileHandle)) {
                                    throw new ApplicationException(
                                        string.Format("{0}. Last Win32 Error was {1}", "Failed to close handle for 'SharedFile'", Marshal.GetLastWin32Error()));
                                }
                                sessionSharedFileHandle = IntPtr.Zero;
                            }

                            // Unmap SharedMem
                            if (sessionSharedMemoryHandle != IntPtr.Zero) {
                                if (!Kernel32.UnmapViewOfFile(sessionSharedMemoryHandle)) {
                                    throw new ApplicationException(
                                        string.Format(
                                            "{0}. Last Win32 Error was {1}", "Failed to unmap view for slot 'DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                                }
                                sessionSharedMemoryHandle = IntPtr.Zero;
                            }

                            // Close SharedFile
                            if (globalSharedFileHandle != IntPtr.Zero) {
                                if (!Kernel32.CloseHandle(globalSharedFileHandle)) {
                                    throw new ApplicationException(
                                        string.Format("{0}. Last Win32 Error was {1}", "Failed to close handle for 'SharedFile'", Marshal.GetLastWin32Error()));
                                }
                                globalSharedFileHandle = IntPtr.Zero;
                            }

                            // Unmap SharedMem
                            if (globalSharedMemoryHandle != IntPtr.Zero) {
                                if (!Kernel32.UnmapViewOfFile(globalSharedMemoryHandle)) {
                                    throw new ApplicationException(
                                        string.Format(
                                            "{0}. Last Win32 Error was {1}", "Failed to unmap view for slot 'Global\\DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                                }
                                globalSharedMemoryHandle = IntPtr.Zero;
                            }
                        }, _cancellationTokenSource.Token);

                    Task.Factory.StartNew(() => {
                        // handle events on seperate task to minimize the work that is done blocking the handles
                        Tuple<int, DateTime, string> item = null;

                        while (WaitHandle.WaitAny(new[] {
                            dataAvailable, _cancellationTokenSource.Token.WaitHandle
                        }) == 0) {
                            lock (queue) {
                                if (queue.Count > 0) {
                                    item = queue.Dequeue();
                                }
                                if (queue.Count == 0) {
                                    dataAvailable.Reset();
                                }
                            }

                            if (item == null || OnOutputDebugString == null) {
                                continue;
                            }

                            try {
                                OnOutputDebugString(new OutputDebugStringEventArgs(item.Item1, item.Item2, item.Item3));
                            } catch {
                                // if it's taken, good, if not--well too bad!
                            }
                        }
                    }, _cancellationTokenSource.Token);
                }
            }
        }
Esempio n. 35
0
        /// <summary>
        /// Waits on 'waitEvent' with a timeout of 'millisceondsTimeout. Before the wait 'numWaiters' is incremented and is 
        /// restored before leaving this routine.
        /// </summary>
        private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
        {
            waitEvent.Reset();
            numWaiters++;

            bool waitSuccessful = false;

            ExitMyLock();      // Do the wait outside of any lock 

            try
            {
                if (!waitEvent.WaitOne(millisecondsTimeout))
                {
                    const string error = "ReaderWriterLock timeout expired";
                    Log.ErrorWithData(error);
                    throw new InvalidOperationException(error);
                }

                waitSuccessful = true;
            }
            finally
            {
                EnterMyLock();

                --numWaiters;

                if (!waitSuccessful) // We are going to throw for some reason.  Exit myLock. 
                {
                    ExitMyLock();
                }
            }
        }
Esempio n. 36
0
        public void DispatchAndWait(EventWaitHandle waitHandle, Action action, DispatcherPriority priority = DispatcherPriority.Normal) {
            Dispatcher dispatcher = ((FrameworkElement)ReplWindow.TextView).Dispatcher;
            waitHandle.Reset();

            dispatcher.Invoke(new Action(() => {
                action();
                waitHandle.Set();
            }), priority);

            Assert.IsTrue(waitHandle.WaitOne(500));
        }
Esempio n. 37
0
        static int Main(string[] args)  // :обновление
        {
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));

            repairUpdateExe();
            var repair = args.Length == 0 || (args.Length == 1 && args[0] == "-repair");

            if (Repair(repair) && repair)
            {
                Console.WriteLine("repair started - succes");
                return(40);
            }

            if (args.Length > 5 || args.Length < 4)
            {
                writeHelp();
                return(1);
            }

            mainMutexForLog.WaitOne();
            addBootRun();

            Semaphore s = null;                  //new System.Threading.Semaphore(50, 50, "vs8.ru updator semaphore");
            Mutex     syncSemaphoreMutex = null;
            int       sCount = 0, rCount = 0, mCount = 0;
            bool      updatorUpdate = false;

            try
            {
                if (args[1] == "vs8.ru updator semaphore")
                {
                    main.Set();
                    sCount        = 50;
                    updatorUpdate = true;
                }
                else
                {
                    sCount = Int32.Parse(args[2]);
                }


                if (args[1].Length > 0)
                {
                    s = new Semaphore(sCount, sCount, args[1]);
                    syncSemaphoreMutex = new Mutex(false, args[1] + " umove sync mutex");
                }

                if (syncSemaphoreMutex != null)
                {
                    if (!syncSemaphoreMutex.WaitOne(0))
                    {
                        return(32);
                    }

                    mCount = 1;
                }

                var RepairInfo = setRepairInfo(args);
                if (s != null)
                {
                    rCount = blockSemaphore(s, sCount);
                }

                var returned = umoveProcess(args);

                if (returned == 0)
                {
                    Console.WriteLine("success");
                }
                else
                {
                    Console.WriteLine("failure with code " + returned);
                }
                File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Исполнено с кодом " + returned, getArgumentsFromArgArray(args)));

                if (updatorUpdate)
                {
                    File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Стартуем ./updatorvs8.exe -umove", getArgumentsFromArgArray(args)));
                    Process.Start("updatorvs8.exe", "-umove");
                }

                if (args[3].Length > 0)
                {
                    if (args.Length == 4)
                    {
                        File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Стартуем " + args[3], getArgumentsFromArgArray(args)));
                        Process.Start(args[3]);
                    }
                    else
                    {
                        File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Стартуем " + args[3] + " " + args[4], getArgumentsFromArgArray(args)));
                        Process.Start(args[3], args[4]);
                    }
                }
                ClearRepairInfo(args, RepairInfo);

                deleteBootRun();
                File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Исполнено и удалено из аварийного восстановления", getArgumentsFromArgArray(args)));

                truncateLog(new FileInfo(errorLogFileName));

                return(returned);
            }
            finally
            {
                if (s != null)
                {
                    releaseSemaphore(s, rCount);
                    s.Close();
                }

                if (syncSemaphoreMutex != null)
                {
                    if (mCount > 0)
                    {
                        syncSemaphoreMutex.ReleaseMutex();
                    }
                    syncSemaphoreMutex.Close();
                }

                main.Reset();
                main.Close();
                mainMutexForLog.ReleaseMutex();
                mainMutexForLog.Close();
            }
        }
Esempio n. 38
0
        protected override void Handle(MercuryPacket packet)
        {
            using var stream = new MemoryStream(packet.Payload);
            int seqLength = getShort(packet.Payload, (int)stream.Position, true);

            stream.Seek(2, SeekOrigin.Current);
            long seq    = 0;
            var  buffer = packet.Payload;

            switch (seqLength)
            {
            case 2:
                seq = getShort(packet.Payload, (int)stream.Position, true);
                stream.Seek(2, SeekOrigin.Current);
                break;

            case 4:
                seq = getInt(packet.Payload, (int)stream.Position, true);
                stream.Seek(4, SeekOrigin.Current);
                break;

            case 8:
                seq = getLong(packet.Payload, (int)stream.Position, true);
                stream.Seek(8, SeekOrigin.Current);
                break;
            }


            byte flags = packet.Payload[(int)stream.Position];

            stream.Seek(1, SeekOrigin.Current);
            short parts = getShort(packet.Payload, (int)stream.Position, true);

            stream.Seek(2, SeekOrigin.Current);



            _partials.TryGetValue(seq, out var partial);
            if (partial == null || flags == 0)
            {
                partial = new BytesArrayList();
                _partials.TryAdd(seq, partial);
            }

            Debug.WriteLine($"Handling packet, cmd: {packet.Cmd}, seq: {seq}, flags: {flags}, parts: {parts}");

            for (int j = 0; j < parts; j++)
            {
                short size = getShort(packet.Payload, (int)stream.Position, true);
                stream.Seek(2, SeekOrigin.Current);

                byte[] buffer2 = new byte[size];

                int end = buffer2.Length;
                for (int z = 0; z < end; z++)
                {
                    byte a = packet.Payload[(int)stream.Position];
                    stream.Seek(1, SeekOrigin.Current);
                    buffer2[z] = a;
                }

                partial.Add(buffer2);
            }

            if (flags != 1)
            {
                return;
            }

            _partials.TryRemove(seq, out partial);

            Header header;

            try
            {
                header = Header.Parser.ParseFrom(partial.First());
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Couldn't parse header! bytes: {Utils.bytesToHex(partial.First())}");
                throw ex;
            }

            var resp = new MercuryResponse(header, partial);

            switch (packet.Cmd)
            {
            case MercuryPacket.Type.MercuryEvent:
                bool dispatched = false;
                lock (_subscriptions)
                {
                    foreach (var sub in _subscriptions)
                    {
                        if (sub.Matches(header.Uri))
                        {
                            sub.Dispatch(resp);
                            dispatched = true;
                        }
                    }
                }

                if (!dispatched)
                {
                    Debug.WriteLine(
                        $"Couldn't dispatch Mercury event seq: {seq}, uri: {header.Uri}, code: {header.StatusCode}, payload: {resp.Payload.ToHex()}");
                }

                break;

            case MercuryPacket.Type.MercuryReq:
            case MercuryPacket.Type.MercurySub:
            case MercuryPacket.Type.MercuryUnsub:
                _callbacks.TryRemove(seq, out var val);
                if (val != null)
                {
                    val.Response(resp);
                }
                else
                {
                    Debug.WriteLine(
                        $"Skipped Mercury response, seq: {seq}, uri: {header.Uri}, code: {header.StatusCode}");
                }

                lock (_removeCallbackLock)
                {
                    _removeCallbackLock.Reset();
                }
                break;

            default:
                Debugger.Break();
                break;
            }
        }
Esempio 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");
            }

            Watch sw = Watch.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)
                    {
                        handle.WaitOne(Math.Min(Math.Max(millisecondsTimeout - (int)sw.ElapsedMilliseconds, 1), deepSleepTime));
                    }
                    else
                    {
                        wait.SpinOnce();
                    }
                }
            } while (true);

            return(true);
        }
Esempio n. 40
0
    public void NameRequiredIsNotBrokenAfterLookupCustomer()
    {
      // test that Name is revalidated as it is an affected property of LookupCustomer rule 
      // that runs when CustomerId is set.
      string ruleSet = "LookupAndNameRequired";
      string err1;
      var actual = RuleBaseClassesRoot.NewEditableRoot(ruleSet);
      err1 = ((IDataErrorInfo)actual)[RuleBaseClassesRoot.NameProperty.Name];

      Assert.IsFalse(actual.IsSelfValid);   // is broken before we set customerid

      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.IsTrue(actual.IsSelfValid);    // is valid after 
    }
Esempio n. 41
0
        /// <summary>
        /// Waits on 'waitEvent' with a timeout
        /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
        /// </summary>
        private bool WaitOnEvent(
            EventWaitHandle waitEvent,
            ref uint numWaiters,
            TimeoutTracker timeout,
            bool isWriteWaiter)
        {
#if DEBUG
            Debug.Assert(MyLockHeld);
#endif
            waitEvent.Reset();
            numWaiters++;
            _fNoWaiters = false;

            //Setting these bits will prevent new readers from getting in.
            if (_numWriteWaiters == 1)
            {
                SetWritersWaiting();
            }
            if (_numWriteUpgradeWaiters == 1)
            {
                SetUpgraderWaiting();
            }

            bool waitSuccessful = false;
            ExitMyLock();      // Do the wait outside of any lock

            try
            {
                waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
            }
            finally
            {
                EnterMyLock();
                --numWaiters;

                if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
                {
                    _fNoWaiters = true;
                }

                if (_numWriteWaiters == 0)
                {
                    ClearWritersWaiting();
                }
                if (_numWriteUpgradeWaiters == 0)
                {
                    ClearUpgraderWaiting();
                }

                if (!waitSuccessful)        // We may also be about to throw for some reason.  Exit myLock.
                {
                    if (isWriteWaiter && _numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && !_fNoWaiters)
                    {
                        // Write waiters block read waiters from acquiring the lock. Since this was the last write waiter and
                        // there is a read waiter, wake up the appropriate read waiters.
                        ExitAndWakeUpAppropriateReadWaiters();
                    }
                    else
                    {
                        ExitMyLock();
                    }
                }
            }
            return(waitSuccessful);
        }
        void ReadThread(ThreadContext ctx)
            {
            System.Threading.Thread.CurrentThread.Name = "IPConnection.ReadThread";

            EventWaitHandle      asyncReadCompleteEvent = new EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);
            SocketAsyncEventArgs socketAsyncEventArgs   = new SignallingSocketEventArgs(asyncReadCompleteEvent);
            byte[]               rgbBuffer              = new byte[64];

            socketAsyncEventArgs.SetBuffer(rgbBuffer, 0, rgbBuffer.Length);

            try {
                WaitHandle[] waitHandles = new WaitHandle[2];
                waitHandles[0] = asyncReadCompleteEvent;
                waitHandles[1] = ctx.StopEvent;

                bool fStop = false;

                while (!fStop && !ctx.StopRequest)
                    {
                    // Issue an async read
                    //
                    asyncReadCompleteEvent.Reset();
                    bool fAsync = true;
                    this.SocketMonitorLock(() =>
                        {
                        fAsync = this.socket.ReceiveAsync(socketAsyncEventArgs);
                        });
                    if (!fAsync)
                        {
                        // IO operation completed synchronously
                        asyncReadCompleteEvent.Set();
                        }

                    this.readThreadRunning.Set();

                    // Wait until either the async read completes or we're asked to stop
                    int iWait = WaitHandle.WaitAny(waitHandles);
                
                    // Process according to which event fired
                    switch (iWait)
                        {
                    case 0: // Async read completed
                        {
                        if (socketAsyncEventArgs.BytesTransferred > 0)
                            {
                            if (socketAsyncEventArgs.SocketError == SocketError.Success)
                                {
                                // Program.Trace("IP Read: incoming packet");
                                ProcessIncomingPacket(rgbBuffer, socketAsyncEventArgs.BytesTransferred);
                                }
                            else
                                {
                                Program.Trace("IP Read: unexpected async result: cb={0} err={1}", socketAsyncEventArgs.BytesTransferred, socketAsyncEventArgs.SocketError);
                                fStop = true;
                                }
                            }
                        else
                            {
                            // Program.Trace("IP Read: read completed with zero bytes");
                            }
                        }
                        break;
                    case 1: // StopEvent 
                        // Program.Trace("async read stop requested");
                        break;
                    // end switch
                        }
                    }
                }
            finally
                {
                }
            }
Esempio n. 43
0
        /// <summary>
        /// Waits on 'waitEvent' with a timeout of 'millisecondsTimeout.  
        /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
        /// </summary>
        /// <param name="waitEvent">
        /// The wait Event.
        /// </param>
        /// <param name="numWaiters">
        /// The num Waiters.
        /// </param>
        /// <param name="millisecondsTimeout">
        /// The milliseconds Timeout.
        /// </param>
        private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
        {
            Debug.Assert(this.MyLockHeld);

            waitEvent.Reset();
            numWaiters++;

            bool waitSuccessful = false;
            this.ExitMyLock(); // Do the wait outside of any lock 
            try
            {
                if (!waitEvent.WaitOne(millisecondsTimeout))
                {
                    throw new InvalidOperationException("ReaderWriterLock timeout expired");
                }

                waitSuccessful = true;
            }
            finally
            {
                this.EnterMyLock();
                --numWaiters;
                if (!waitSuccessful)
                {
                    // We are going to throw for some reason.  Exit myLock. 
                    this.ExitMyLock();
                }
            }
        }
Esempio n. 44
0
        /// <summary>
        /// Run a process
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="process"></param>
        /// <param name="onCallback"></param>
        /// <param name="onError"></param>
        /// <param name="onComplete"></param>
        public static void RunProcess(Filter filter, Action<Action<StringDictionary, ProfilerRuntime>> process, Action<int, byte[]> onCallback, Action<Exception> onError, Action onComplete)
        {
            filter = filter ?? new Filter();
            var tag = (new Random((int)DateTime.UtcNow.Ticks)).Next().ToString();

            var readBufferEvt = new EventWaitHandle(false, EventResetMode.ManualReset, "Local\\MM_ReadBuffer" + tag);
            var bufferReadEvt = new EventWaitHandle(false, EventResetMode.ManualReset, "Local\\MM_BufferRead" + tag);
            var workItemClosedEvt = new AutoResetEvent(false);
            var waitHandles = new WaitHandle[] { workItemClosedEvt, readBufferEvt };

            var includes = string.IsNullOrWhiteSpace(filter.Includes) ? String.Empty.ToCharArray() : filter.Includes.ToCharArray();
            var excludes = string.IsNullOrWhiteSpace(filter.Excludes) ? String.Empty.ToCharArray() : filter.Excludes.ToCharArray();
                
            const int pfs = (32768 * 4) + 4 + 4;

            using (var mmf2 = MemoryMappedFile.CreateOrOpen("Local\\MMProfilerMapBuffer" + tag, 4 + filter.BufferSize + filter.ThresholdSize))
            {
                using (var mmf = MemoryMappedFile.CreateOrOpen("Local\\MMProfilerMapControl" + tag, pfs))
                {
                    var filterAccessor = mmf.CreateViewAccessor(0, pfs, MemoryMappedFileAccess.ReadWrite);

                    var lengthAccessor = mmf2.CreateViewAccessor(0, 4, MemoryMappedFileAccess.ReadWrite);
                    var streamAccessor = mmf2.CreateViewStream(4, filter.BufferSize + filter.ThresholdSize, MemoryMappedFileAccess.ReadWrite);

                    filterAccessor.Write(0, filter.BufferSize);
                    filterAccessor.Write(4, filter.ThresholdSize);
                    filterAccessor.WriteArray(4 + 4, includes, 0, includes.Count());
                    filterAccessor.WriteArray(32768 * 2 + 4 + 4, excludes, 0, excludes.Count());

                    ThreadPool.QueueUserWorkItem((state) =>
                                                     {
                                                         try
                                                         {
                                                             process((dictionary, runtime) =>
                                                                         {
                                                                             if (dictionary == null) return;
                                                                             if (dictionary.ContainsKey("Cor_Profiler") && dictionary.ContainsKey("Cor_Enable_Profiling") && dictionary["Cor_Enable_Profiling"] == "1")
                                                                             {
                                                                                 Logger.WriteInfo("WARNING A PROFILER IS ALREADY REGISTERED!!!");
                                                                             }
                                                                             else
                                                                             {
                                                                                 dictionary["MMProfiler_Tag"] = tag;
                                                                                 dictionary["Cor_Profiler"] =
                                                                                     (runtime ==
                                                                                      ProfilerRuntime.Runtime32)
                                                                                         ? "{36C8D782-F697-45C4-856A-92D05C061A39}"
                                                                                         : "{5D789D88-EEE7-46C4-909F-E39D5606544D}";

                                                                                 dictionary["Cor_Enable_Profiling"] = "1";
                                                                             }
                                                                         });
                                                         }
                                                         finally
                                                         {
                                                             workItemClosedEvt.Set();
                                                         }
                                                     });

                    var data = new byte[filter.BufferSize + filter.ThresholdSize];
                    var length = 0;
                    var error = false;
                    try
                    {
                        bool bTerminate = false;
                        while (!bTerminate)
                        {
                            switch (WaitHandle.WaitAny(waitHandles))
                            {
                                case 0:
                                    bTerminate = true;
                                    break;
                                case 1:
                                    readBufferEvt.Reset();
                    
                                    length = lengthAccessor.ReadInt32(0);
                                    lengthAccessor.Write(0, (Int32)0);
                                    streamAccessor.Read(data, 0, length);
                                    streamAccessor.Seek(0, SeekOrigin.Begin);

                                    bufferReadEvt.Set();
                                    bufferReadEvt.Reset();

                                    onCallback(length, data);
                                    break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        onError(ex);
                        error = true;
                    }
                    finally
                    {
                        if (!error)
                        {
                            length = lengthAccessor.ReadInt32(0);
                            streamAccessor.Read(data, 0, length);
                            onCallback(length, data);
                            onComplete();
                        }
                    }
                }
            }
        }