コード例 #1
0
ファイル: debugAPI.cs プロジェクト: erwincas/monoev3-project
 public static void forward()
 {
     {
         Console.Write ("Hoe ver: ");
         uint cm = uint.Parse (Console.ReadLine ());
         Console.Write ("Hoe snel: ");
         SByte speed = (SByte)int.Parse (Console.ReadLine ());
         Console.WriteLine ("forward " + cm + " cm at " + speed + " % speed");
         //Convert degrees to cm. Bereken eerst de graad/Cm en vul deze in bij de conastanten.
         uint graden = (uint)(cm * graadCmForward);
         //Hier begint de magie
         waitHandle = vehicle.Forward (speed, graden, true);
         //Geef die motor even rust
         waitHandle.WaitOne ();
         string output = cm + " cm vooruit gegaan met een snelheid van " + speed + "%";
         Console.WriteLine (output);
         //Schrijf naar een bestand
         using (System.IO.StreamWriter file =
                    new System.IO.StreamWriter (@"/home/root/apps/NoWait/output.txt", true)) {
             file.WriteLine ("forward");
             file.WriteLine (cm);
             file.WriteLine (speed);
             file.WriteLine ("");
         }
         Thread.Sleep (100);
     }
 }
コード例 #2
0
ファイル: AsyncResult.cs プロジェクト: 85351/dotnet_framework
        protected static TAsyncResult End <TAsyncResult>(IAsyncResult result)
            where TAsyncResult : AsyncResult
        {
            if (result == null)
            {
                throw Fx.Exception.ArgumentNull("result");
            }

            TAsyncResult asyncResult = result as TAsyncResult;

            if (asyncResult == null)
            {
                throw Fx.Exception.Argument("result", InternalSR.InvalidAsyncResult);
            }

            if (asyncResult.endCalled)
            {
                throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultAlreadyEnded));
            }

#if DEBUG
            if (!Fx.FastDebug && asyncResult.endStack == null)
            {
                asyncResult.endStack = new StackTrace();
            }
#endif

            asyncResult.endCalled = true;

            WaitHandle waitHandle = null;

            lock (asyncResult.ThisLock)
            {
                if (!asyncResult.isCompleted)
                {
                    waitHandle = asyncResult.AsyncWaitHandle;
                }
            }

            waitHandle?.WaitOne();

            if (asyncResult.manualResetEvent != null)
            {
                asyncResult.manualResetEvent.Close();
            }

            if (asyncResult.exception != null)
            {
                throw Fx.Exception.AsError(asyncResult.exception);
            }

            return(asyncResult);
        }
コード例 #3
0
 public static void forward(double cm, SByte speed, Boolean brake, Boolean silent)
 {
     //Init vehicle, waitHandle en speaker
     //Go forward with .. cm at .. speed
     LcdConsole.WriteLine ("forward " + cm + " cm at " + speed + " % speed");
     //Convert degrees to cm. Bereken eerst de graad/Cm en vul deze in bij de conastanten.
     uint graden = (uint)(cm * graadCmForward);
     //Hier begint de magie
     waitHandle = vehicle.Forward (speed, graden, brake);
     //Geef die motor even rust
     waitHandle.WaitOne ();
     LcdConsole.WriteLine ("Done moving forward!");
     if (!silent) {
         speaker.Buzz ();
     }
     Thread.Sleep (100);
 }
コード例 #4
0
ファイル: ThreadPool.cs プロジェクト: modulexcite/IL2JS
        public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object state, long millisecondsTimeOutInterval, bool executeOnlyOnce)
        {
            if (executeOnlyOnce != true)
            {
                throw new NotSupportedException("executeOnlyOnce must be true");
            }

            int tickTime = (int)Math.Min(100, millisecondsTimeOutInterval);

            int totalTimeElapsed = 0;
            Timer timer = null;

            timer = new Timer((s) =>
            {
                // Timer will fire every due period...if total time exceeds millisecondsTimeoutInterval then we call the timeoutcallback
                // otherwise we wait...if at any point the waitObject is signaled...than we can abort.
                if (waitObject.WaitOne(0))
                {
                    // Signal is set so no timeout occured
                    timer.Dispose();
                    return;
                }
                else if (totalTimeElapsed > millisecondsTimeOutInterval)
                {
                    // Timeout has occured
                    timer.Dispose();
                    callBack(state, true);
                }
                else
                {
                    totalTimeElapsed += tickTime;
                }
            }, null, tickTime, tickTime);

            return null;
        }
コード例 #5
0
 /// <summary>
 /// Blocks the current thread until the current <see cref="T:System.Threading.WaitHandle"/> is set, using a <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see cref="T:System.Threading.CancellationToken"/>.
 /// </summary>
 ///
 /// <returns>
 /// true if the <see cref="T:System.Threading.WaitHandle"/> was set; otherwise, false.
 /// </returns>
 /// <param name="waitHandle">The wait handle to wait on</param>
 /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.</param>
 /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to observe.</param>
 /// <exception cref="T:System.Threading.OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception>
 /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than <see cref="F:System.Int32.MaxValue"/>.</exception>
 /// <exception cref="T:System.InvalidOperationException">The maximum number of waiters has been exceeded. </exception><exception cref="T:System.ObjectDisposedException">The object has already been disposed or the <see cref="T:System.Threading.CancellationTokenSource"/> that created <paramref name="cancellationToken"/> has been disposed.</exception>
 public static bool WaitOne(this WaitHandle waitHandle, TimeSpan timeout, CancellationToken cancellationToken)
 {
     return(waitHandle.WaitOne((int)timeout.TotalMilliseconds, cancellationToken));
 }
コード例 #6
0
    // this one tests that a WaitOne will wait on a Mutex
    // and then grab it when it is free
    public bool PosTest1()
    {
        bool retVal = false;
        Thread thread = null;

        TestLibrary.TestFramework.BeginScenario("PosTest1: WaitOne returns true when current instance receives a signal");

        // m_Handle is of type WaitHandle
        // Mutex is a subclass of WaitHandle
        using(m_Handle = new Mutex())
        {
        try
        {
            // Spin up a thread.  SignalMutex grabs 
            // the Mutex, then goes to sleep for 5 seconds.  It
            // only releases the mutex after sleeping for those
            // 5 seconds
            thread = new Thread(new ThreadStart(SignalMutex));
            // Start it
            thread.Start();
            // Then put this calling thread to sleep
            // for one second so that it doesn't beat the spawned
            // thread to the mutex
            Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race
            // Now, the spawned thread should already
            // have the mutex and be sleeping on it for several 
            // seconds.  try to grab the mutex now.  We should 
            // simply block until the other thread releases it, 
            // then we should get it.
            // Net result, we should get true back from WaitOne
            if (m_Handle.WaitOne() != true)
            {
                TestLibrary.TestFramework.LogError("001", "WaitOne returns false when current instance receives a signal.");
                retVal = false;

            }
            else
            {
                // got the mutex ok
                retVal = true;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }
        finally
        {
            // Wait for the thread to terminate
            if (null != thread)
            {
                // Wait on that thread
                thread.Join();
            }
        }
        }

        return retVal;
    }
コード例 #7
0
    // this one just tests that a WaitOne will receive
    // a AbandonedMutexException
    public bool NegTest1()
    {
        bool retVal = false;
        Thread thread = null;

        TestLibrary.TestFramework.BeginScenario("NegTest1: AbandonedMutexException should be thrown if a thread exited without releasing a mutex");

        // m_Handle is of type WaitHandle
        // Mutex is a subclass of WaitHandle
        using(m_Handle = new Mutex())
        {
        try
        {
            // Spin up a thread.  SignalMutex grabs 
            // the Mutex, then goes to sleep for 5 seconds.  
            thread = new Thread(new ThreadStart(NeverReleaseMutex));
            // Start it
            thread.Start();
            // Then put this calling thread to sleep
            // for just over one second so that it doesn't beat 
            // the spawned thread to the mutex
            Thread.Sleep(c_DEFAULT_SLEEP_TIME / 3); // To avoid race
            // Now, the spawned thread should already
            // have the mutex and be sleeping on it forever.
            // try to grab the mutex now.  We should simply block until
            // the other thread releases it, which is never.  When that 
            // thread returns from its method, an AbandonedMutexException
            // should be thrown instead
            m_Handle.WaitOne();

            // We should not get here
            TestLibrary.TestFramework.LogError("101", "AbandonedMutexException is not thrown if a thread exited without releasing a mutex");
            retVal = false;
        }
        catch (AbandonedMutexException)
        {
            // Swallow it, this is where we want
            // the test to go
            retVal = true;
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }
        finally
        {
            if (null != thread)
            {
                // The spawned thread is still running.
                // Join on it until it is done
                thread.Join();
            }
        }
        }

        return retVal;
    }
コード例 #8
0
 internal static bool WaitOne(this WaitHandle waitHandle, TimeSpan timeSpan, bool exitContext) => waitHandle.WaitOne(timeSpan);
コード例 #9
0
 /// <summary>
 /// Waits for the primary(host) game instance to signal that it has finished loading. This also signals at what point the shared settings memory is safe to close on this process.
 /// </summary>
 public void WaitForHostInstance()
 {
     waitHandle.WaitOne();
 }
コード例 #10
0
        // Returns: True if all messages are proccessed. False if at least one new message is not processed.
        private bool ProcessMessagesPop(Pop3Client client, int max_messages_per_session, WaitHandle stop_event, out int processed_messages_count)
        {
            UpdateTimeCheckedIfNeeded();
            processed_messages_count = max_messages_per_session;
            var bad_messages_exist = false;
            Dictionary <int, string> new_messages;
            var stored_uidl_list = new Dictionary <int, string>();
            var stored_md5_list  = new Dictionary <int, string>();

            InvokeGetStoredMessagesUIDL_MD5(stored_uidl_list, stored_md5_list);

            if (!IsUidlSupported)
            {
                _log.Info("UIDL is not supported! Account '{0}' has been skiped.", Account.EMail);
                return(true);
            }

            var email_ids = client.GetUniqueIds();

            new_messages =
                email_ids
                .Where(id => !stored_uidl_list.Values.Contains(id.UniqueId))
                .OrderBy(id => id.Index)
                .ToDictionary(id => id.Index, id => id.UniqueId);


            var quota_error_flag = false;

            if (client.IsConnected)
            {
                if (new_messages.Count == 0)
                {
                    _log.Debug("New messages not found.\r\n");
                }
                else
                {
                    _log.Debug("Found {0} new messages.\r\n", new_messages.Count);

                    if (new_messages.Count > 1)
                    {
                        _log.Debug("Calculating order");

                        try
                        {
                            var first_header = client.RetrieveHeaderObject(new_messages.First().Key);
                            var last_header  = client.RetrieveHeaderObject(new_messages.Last().Key);

                            if (first_header.Date < last_header.Date)
                            {
                                _log.Debug("Account '{0}' order is DESC", Account.EMail.Address);
                                new_messages = new_messages
                                               .OrderByDescending(item => item.Key) // This is to ensure that the newest message would be handled primarily.
                                               .ToDictionary(id => id.Key, id => id.Value);
                            }
                            else
                            {
                                _log.Debug("Account '{0}' order is ASC", Account.EMail.Address);
                            }
                        }
                        catch (Exception)
                        {
                            _log.Warn("Calculating order skipped! Account '{0}' order is ASC", Account.EMail.Address);
                        }
                    }

                    var skip_on_date = Account.BeginDate != MailBoxManager.MIN_BEGIN_DATE;

                    var skip_break_on_date = MailQueueItemSettings.PopUnorderedDomains.Contains(Account.Server.ToLowerInvariant());

                    foreach (var new_message in new_messages)
                    {
                        try
                        {
                            if (stop_event.WaitOne(0))
                            {
                                break;
                            }

                            if (max_messages_per_session == 0)
                            {
                                _log.Debug("Limit of max messages per session is exceeded!");
                                break;
                            }

                            _log.Debug("Processing new message\tid={0}\t{1}\t",
                                       new_message.Key,
                                       (IsUidlSupported ? "UIDL: " : "MD5: ") + new_message.Value);

                            if (!client.IsConnected)
                            {
                                _log.Warn("POP3 server is disconnected. Skip another messages.");
                                bad_messages_exist = true;
                                break;
                            }

                            var message = client.RetrieveMessageObject(new_message.Key);
                            UpdateTimeCheckedIfNeeded();

                            if (message.Date < Account.BeginDate && skip_on_date)
                            {
                                if (!skip_break_on_date)
                                {
                                    _log.Info("Skip other messages older then {0}.", Account.BeginDate);
                                    break;
                                }
                                _log.Debug("Skip message (Date = {0}) on BeginDate = {1}", message.Date, Account.BeginDate);
                                continue;
                            }

                            var header_md5 = string.Empty;

                            if (IsUidlSupported)
                            {
                                var unique_identifier = string.Format("{0}|{1}|{2}|{3}",
                                                                      message.From.Email,
                                                                      message.Subject,
                                                                      message.DateString,
                                                                      message.MessageId);

                                header_md5 = unique_identifier.GetMD5();

                                if (!message.To.Exists(email =>
                                                       email.Email
                                                       .ToLowerInvariant()
                                                       .Equals(message.From.Email
                                                               .ToLowerInvariant())))
                                {
                                    var found_message_id = stored_md5_list
                                                           .Where(el => el.Value == header_md5)
                                                           .Select(el => el.Key)
                                                           .FirstOrDefault();

                                    if (found_message_id > 0)
                                    {
                                        InvokeOnUpdateUidl(found_message_id, new_message.Value);
                                        continue; // Skip saving founded message
                                    }
                                }
                            }

                            InvokeOnRetrieve(message,
                                             MailFolder.Ids.inbox,
                                             IsUidlSupported ? new_message.Value : "",
                                             IsUidlSupported ? header_md5 : new_message.Value);
                        }
                        catch (IOException io_ex)
                        {
                            if (io_ex.Message.StartsWith("Unable to write data to the transport connection") ||
                                io_ex.Message.StartsWith("Unable to read data from the transport connection"))
                            {
                                _log.Error("ProcessMessages() Account='{0}': {1}",
                                           Account.EMail.Address, io_ex.ToString());

                                max_messages_per_session = 0; //It needed for stop messsages proccessing.
                                bad_messages_exist       = true;
                                break;
                            }
                        }
                        catch (MailBoxOutException ex)
                        {
                            _log.Info("ProcessMessages() Tenant={0} User='******' Account='{2}': {3}",
                                      Account.TenantId, Account.UserId, Account.EMail.Address, ex.Message);
                            bad_messages_exist = true;
                            break;
                        }
                        catch (TenantQuotaException qex)
                        {
                            _log.Info("Tenant {0} quota exception: {1}", Account.TenantId, qex.Message);
                            quota_error_flag = true;
                        }
                        catch (Exception e)
                        {
                            bad_messages_exist = true;
                            _log.Error("ProcessMessages() Tenant={0} User='******' Account='{2}', MailboxId={3}, MessageIndex={4}, UIDL='{5}' Exception:\r\n{6}\r\n",
                                       Account.TenantId, Account.UserId, Account.EMail.Address, Account.MailBoxId, new_message.Key, new_message.Value, e.ToString());
                        }

                        UpdateTimeCheckedIfNeeded();
                        max_messages_per_session--;
                    }
                }
            }
            else
            {
                _log.Debug("POP3 server is disconnected.");
                bad_messages_exist = true;
            }

            InvokeOnDone(quota_error_flag);

            processed_messages_count -= max_messages_per_session;
            return(!bad_messages_exist && max_messages_per_session > 0);
        }
コード例 #11
0
ファイル: debugAPI.cs プロジェクト: erwincas/monoev3-project
 public static void right()
 {
     Console.Write("Aantal graden: ");
     double graden = double.Parse(Console.ReadLine());
     Console.Write ("Hoe snel: ");
     SByte speed = (SByte)int.Parse(Console.ReadLine());
     Console.WriteLine ("Turning " + graden + " degrees right");
     //Convert degrees to cm. Bereken eerst de graad/Cm en vul deze in bij de constanten
     uint gradencorrect = (uint)(graden * graadCmTurn); //Want graden * graadCm geeft de precieze draai.
     //Hier begint de magie
     waitHandle = vehicle.SpinRight(speed,gradencorrect,true);
     //Geef die motor even rust
     waitHandle.WaitOne();
     string output = graden + " naar rechts gedraaid met een snelheid van " + speed + "%";
     Console.WriteLine (output);
     using (System.IO.StreamWriter file =
         new System.IO.StreamWriter (@"/home/root/apps/NoWait/output.txt", true)) {
         file.WriteLine ("right");
         file.WriteLine (graden);
         file.WriteLine (speed);
         file.WriteLine ("");
     }
     Thread.Sleep (100);
 }
コード例 #12
0
ファイル: RabNetLan.cs プロジェクト: x-plora/miakro911
        private Stream sendTcpMessage(string message)
        {
            TcpClient client = new TcpClient();

            client.Connect(_rdAddress, UPDATE_FILES_PORT);
            NetworkStream netStream = client.GetStream();
            Stream        result    = null;

#if !NOCATCH
            try
            {
#endif
            byte[] buffer = makeSendBuffer(message);
            netStream.Write(buffer, 0, buffer.Length);

            long totalRecBytesCount = 0;
            long lenght             = -1;
            TcpStreamDataType dtype;
            int offset = 0;

            do
            {
                if (offset == 0)
                {
                    buffer = new byte[65536];
                }
                int          len         = (lenght < 0 || buffer.Length < (lenght - totalRecBytesCount)) ? buffer.Length : (int)(lenght - totalRecBytesCount);
                IAsyncResult asyncResult = netStream.BeginRead(buffer, offset, (len - offset), null, null);

                WaitHandle waiter = asyncResult.AsyncWaitHandle;
                bool       good   = waiter.WaitOne(10000, true);
                if (!good)
                {
                    continue;
                }

                int recBytesCount = netStream.EndRead(asyncResult) + offset;
                if (lenght == -1)
                {
                    if (recBytesCount < DATATYPE_OFFSET)
                    {
                        offset = recBytesCount;
                        continue;
                    }
                    offset = 0;
                    buffer = parseSendBuffer(buffer, ref recBytesCount, out lenght, out dtype);
                    ///
                    switch (dtype)
                    {
                    case TcpStreamDataType.ErrorMessage: throw new RabLanException(Encoding.UTF8.GetString(buffer));

                    case TcpStreamDataType.File:
                        string tmpFile = Path.Combine(Path.GetTempPath(), String.Format("rabnet_{0:s}.tmp", Guid.NewGuid().ToString()));
                        result = new FileStream(tmpFile, FileMode.CreateNew, FileAccess.ReadWrite);
                        break;

                    default: result = new MemoryStream(); break;
                    }
                }

                result.Write(buffer, 0, recBytesCount);
                totalRecBytesCount += recBytesCount;
            }while (lenght != totalRecBytesCount);
#if !NOCATCH
        }

        catch (Exception exc)
        {
            _logger.Error(exc);
        }
        finally
        {
#endif
            netStream.Close();
#if !NOCATCH
        }
#endif
            result.Position = 0;
            return(result);
        }
コード例 #13
0
    public static int Main(String [] args)
    {
        int        rValue = 100;
        WaitHandle wh     = null;

        Console.WriteLine("Test AutoResetEvent for expected NullRef Exceptions");
        Console.WriteLine( );


//      try {
// #pragma warning disable 618
//          wh.Handle = new IntPtr(1);
// #pragma warning restore 618
//          rValue = 1;
//      }
//      catch (NullReferenceException) {
//          Console.WriteLine("Caught NullReferenceException   (wh.Handle(new IntPtr(1)))");
//      }
//      try {
// #pragma warning disable 618
//          IntPtr iptr = wh.Handle;
// #pragma warning restore 618
//          rValue = 2;
//      }
//      catch (NullReferenceException) {
//          Console.WriteLine("Caught NullReferenceException   (IntPtr iptr = wh.Handle)");
//      }

        // try {
        //  wh.Close();
        //  rValue = 3;
        // }
        // catch (NullReferenceException) {
        //  Console.WriteLine("Caught NullReferenceException   (wh.Close())");
        // }

        try {
            wh.Equals(new ManualResetEvent(true));
            rValue = 4;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (wh.Equals(new ManualResetEvent()))");
        }

        try {
            wh.GetHashCode();
            rValue = 5;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (wh.GetHasCode())");
        }

        // try {
        //  wh.GetLifetimeService();
        //  rValue = 6;
        // }
        // catch (NullReferenceException) {
        //  Console.WriteLine("Caught NullReferenceException   (wh.GetLifetimeService())");
        // }

        try {
            wh.GetType();
            rValue = 7;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (wh.GetType())");
        }

        // try {
        //  wh.InitializeLifetimeService();
        //  rValue = 8;
        // }
        // catch (NullReferenceException) {
        //  Console.WriteLine("Caught NullReferenceException   (wh.InitializeLifeTimeService())");
        // }

        try {
            wh.ToString();
            rValue = 11;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (wh.ToString())");
        }

        try {
            wh.WaitOne();
            rValue = 12;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (wh.WaitOne())");
        }

        try {
            wh.WaitOne(1000);            //,true);
            rValue = 13;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (wh.WaitOne(int))");
        }

        // try {
        //  wh.WaitOne(1000,false);
        //  rValue = 14;
        // }
        // catch (NullReferenceException) {
        //  Console.WriteLine("Caught NullReferenceException   (wh.WaitOne(int,bool))");
        // }

        try {
            wh.WaitOne(new TimeSpan(1000));            //,true);
            rValue = 15;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (wh.WaitOne(TimeSpan,bool))");
        }

        // try {
        //  wh.WaitOne(new TimeSpan(1000),false);
        //  rValue = 16;
        // }
        // catch (NullReferenceException) {
        //  Console.WriteLine("Caught NullReferenceException   (wh.WaitOne(TimeSpan,bool))");
        // }

        Console.WriteLine("Return Code == {0}", rValue);
        return(rValue);
    }
コード例 #14
0
ファイル: TimeoutTimer.cs プロジェクト: guiltedom/donkirkby
 /// <summary>
 /// Blocks the current thread until the WaitHandle receives a signal or the
 /// timer times out.
 /// </summary>
 /// <param name="waitHandle">The wait handle to block on.</param>
 /// <returns>true if the wait handle receives a signal; otherwise false.</returns>
 /// <remarks>
 /// This is equivalent to WaitHandle.WaitOne(Timeout), but it allows you
 /// to write unit tests that make the timer wait until the unit test
 /// tells it to time out.
 /// </remarks>
 public virtual bool WaitOne(WaitHandle waitHandle)
 {
     return(waitHandle.WaitOne(Timeout));
 }
コード例 #15
0
        /// <summary>
        /// Wait for a handle and pump messages with DoEvents
        /// by noseratio - http://stackoverflow.com/a/20461655/1768303
        /// </summary>
        public static bool WaitWithDoEvents(this WaitHandle handle, CancellationToken token, int timeout)
        {
            if (SynchronizationContext.Current as System.Windows.Forms.WindowsFormsSynchronizationContext == null)
            {
                // http://stackoverflow.com/a/19555959
                throw new ApplicationException("Internal error: WaitWithDoEvents must be called on a thread with WindowsFormsSynchronizationContext.");
            }

            const uint EVENT_MASK = Win32.QS_ALLINPUT;

            IntPtr[] handles = { handle.SafeWaitHandle.DangerousGetHandle() };

            // track timeout if not infinite
            Func <bool> hasTimedOut      = () => false;
            int         remainingTimeout = timeout;

            if (timeout != Timeout.Infinite)
            {
                // can't use Environment.TickCount, it is integer and may have a problem with timer wrapping
                uint startTick = Win32.GetTickCount();
                hasTimedOut = () =>
                {
                    var lapse = unchecked ((int)(Win32.GetTickCount() - startTick));
                    remainingTimeout = Math.Max(timeout - lapse, 0);
                    return(remainingTimeout == 0);
                };
            }

            while (true)
            {
                token.ThrowIfCancellationRequested();  // throw if cancellation requested from outside

                if (handle.WaitOne(0))                 // instant check
                {
                    return(true);
                }

                System.Windows.Forms.Application.DoEvents();

                if (hasTimedOut())
                {
                    return(false);                                 // timed out
                }
                if ((Win32.GetQueueStatus(EVENT_MASK) >> 16) != 0) // high word is non-zero if an input/message is still in the queue
                {
                    continue;
                }

                // raise Idle event
                System.Windows.Forms.Application.RaiseIdle(EventArgs.Empty);

                if (hasTimedOut())
                {
                    return(false);
                }

                // wait for either a Windows message or the handle
                // MsgWaitForMultipleObjectsEx with MWMO_INPUTAVAILABLE returns even if there's a message in the message queue already seen but not removed
                var result = Win32.MsgWaitForMultipleObjectsEx(1, handles, (uint)remainingTimeout, EVENT_MASK, Win32.MWMO_INPUTAVAILABLE);
                if (result == Win32.WAIT_OBJECT_0 || result == Win32.WAIT_ABANDONED_0)
                {
                    return(true);                    // handle signalled
                }
                if (result == Win32.WAIT_TIMEOUT)
                {
                    return(false);                     // timed out
                }
                if (result == Win32.WAIT_OBJECT_0 + 1) // an input/message pending
                {
                    continue;
                }
                // unexpected result
                throw new InvalidOperationException();
            }
        }
コード例 #16
0
 public static bool WaitOne(this WaitHandle handle, CancellationToken cancellationToken)
 => handle.WaitOne(Timeout.Infinite, cancellationToken);
コード例 #17
0
    public static void ExpectNoEvent(WaitHandle eventOccurred, string eventName, int timeout = WaitForUnexpectedEventTimeout)
    {
        string message = String.Format("Should not observe a {0} event within {1}ms", eventName, timeout);

        Assert.False(eventOccurred.WaitOne(timeout), message);
    }
コード例 #18
0
ファイル: ExtensionMethods.cs プロジェクト: EnergonV/BestCS
 public static bool WaitOne(this WaitHandle waitHandle, int millisecondsTimeout, bool exitContext)
 {
     return(waitHandle.WaitOne(millisecondsTimeout));
 }
コード例 #19
0
        // Returns: maxMessagesPerSession minus count of downloaded messages or zero if limit excided
        private int ProcessMessages(Mailbox mb,
                                    int folder_id,
                                    int last_uid,
                                    int max_messages_per_session,
                                    WaitHandle stop_event,
                                    string[] tags_names)
        {
            UpdateTimeCheckedIfNeeded();
            int[] uids_collection;

            try
            {
                uids_collection = mb.UidSearch("UID " + (0 != last_uid ? last_uid : 1) + ":*")
                                  .Where(uid => uid != last_uid)
                                  .ToArray();

                if (!uids_collection.Any())
                {
                    throw new Exception("Empty folder");
                }
            }
            catch (Exception)
            {
                _log.Info("New messages not found.");
                return(max_messages_per_session);
            }

            var stored_uid_list = new Dictionary <int, string>();
            var stored_md5_list = new Dictionary <int, string>();

            InvokeGetStoredMessagesUIDL_MD5(stored_uid_list, stored_md5_list);

            var tags_hash = tags_names.Aggregate(string.Empty, (current, name) => current + name).GetMD5Hash();

            var new_messages = uids_collection
                               .Select(
                item_uid =>
                new
            {
                uid  = item_uid,
                uidl = tags_names.Any()
                                ? string.Format("{0}-{1}-{2}-{3}", item_uid, folder_id, mb.UidValidity, tags_hash)
                                : string.Format("{0}-{1}-{2}", item_uid, folder_id, mb.UidValidity)
            })
                               .Where(msg => !stored_uid_list.Values.Contains(msg.uidl))
                               .OrderByDescending(msg => msg.uid)
                               .ToDictionary(msg => msg.uid, id => id.uidl);

            var quota_error_flag       = false;
            var update_folder_uid_flag = new_messages.Any();

            int[] tags_ids = null;
            var   message_ids_for_tag_update = new List <int>();
            var   tags_retrieved             = false;

            foreach (var new_message in new_messages)
            {
                int last_founded_message_id = -1;
                try
                {
                    if (stop_event.WaitOne(0))
                    {
                        _log.Debug("Stop event occure.");
                        break;
                    }

                    if (max_messages_per_session == 0)
                    {
                        _log.Debug("Limit of max messages per session is exceeded!");
                        update_folder_uid_flag = false;
                        break;
                    }

                    // flags should be retrieved before message fetch - because mail server
                    // could add seen flag right after message was retrieved by us
                    var flags = mb.Fetch.UidFlags(new_message.Key);

                    //Peek method didn't set \Seen flag on mail
                    var message = mb.Fetch.UidMessageObjectPeek(new_message.Key);
                    UpdateTimeCheckedIfNeeded();

                    if (message.Date < Account.BeginDate)
                    {
                        _log.Debug("Skip message (Date = {0}) on BeginDate = {1}", message.Date, Account.BeginDate);
                        break;
                    }

                    var unique_identifier = string.Format("{0}|{1}|{2}|{3}",
                                                          message.From.Email,
                                                          message.Subject,
                                                          message.DateString,
                                                          message.MessageId);

                    var header_md5 = unique_identifier.GetMD5();

                    //Get tags ids for folder before message proccessing only once
                    if (!tags_retrieved)
                    {
                        tags_ids       = tags_names.Any() ? InvokeOnGetOrCreateTags(tags_names) : null;
                        tags_retrieved = true;
                    }

                    if (folder_id == MailFolder.Ids.inbox || !message.To.Exists(email =>
                                                                                email.Email.ToLowerInvariant()
                                                                                .Equals(message.From.Email.ToLowerInvariant())
                                                                                )
                        )
                    {
                        var found_message_id = stored_md5_list
                                               .Where(el => el.Value == header_md5)
                                               .Select(el => el.Key)
                                               .FirstOrDefault();

                        if (found_message_id > 0)
                        {
                            InvokeOnUpdateUidl(found_message_id, new_message.Value);
                            last_founded_message_id = found_message_id;
                            message_ids_for_tag_update.Add(found_message_id); //Todo: Remove id if exception happened
                            continue;                                         // Skip saving founded message
                        }
                    }

                    var unread = null == flags["seen"];
                    InvokeOnRetrieve(message, folder_id, new_message.Value, header_md5, unread, tags_ids);
                }
                catch (IOException io_ex)
                {
                    if (io_ex.Message.StartsWith("Unable to write data to the transport connection") ||
                        io_ex.Message.StartsWith("Unable to read data from the transport connection"))
                    {
                        _log.Error("ProcessMessages() Account='{0}': {1}",
                                   Account.EMail.Address, io_ex.ToString());
                        message_ids_for_tag_update.Remove(last_founded_message_id);
                        update_folder_uid_flag   = false;
                        max_messages_per_session = 0; // stop checking other mailboxes

                        break;
                    }
                }
                catch (MailBoxOutException ex)
                {
                    _log.Info("ProcessMessages() Account='{0}': {1}",
                              Account.EMail.Address, ex.Message);
                    message_ids_for_tag_update.Remove(last_founded_message_id);
                    update_folder_uid_flag   = false;
                    max_messages_per_session = 0; // stop checking other mailboxes

                    break;
                }
                catch (TenantQuotaException qex)
                {
                    _log.Info("Tenant {0} quota exception: {1}", Account.TenantId, qex.Message);
                    message_ids_for_tag_update.Remove(last_founded_message_id);
                    quota_error_flag       = true;
                    update_folder_uid_flag = false;
                }
                catch (Exception e)
                {
                    _log.Error("ProcessMessages() Account='{0}', MessageId={1} Exception:\r\n{2}\r\n",
                               Account.EMail.Address, new_message, e.ToString());
                    update_folder_uid_flag = false;
                    message_ids_for_tag_update.Remove(last_founded_message_id);
                }

                UpdateTimeCheckedIfNeeded();
                max_messages_per_session--;
            }

            if (tags_ids != null && tags_ids.Length > 0 && message_ids_for_tag_update.Count > 0)
            {
                InvokeOnUpdateMessagesTags(Account.TenantId, Account.UserId, tags_ids, message_ids_for_tag_update.ToArray());
            }

            if (update_folder_uid_flag)
            {
                var max_uid = new_messages.Keys.Max();

                if (Account.ImapFolders.Keys.Contains(mb.Name))
                {
                    Account.ImapFolders[mb.Name] = max_uid;
                }
                else
                {
                    Account.ImapFolders.Add(mb.Name, max_uid);
                }

                Account.ImapFolderChanged = true;
            }

            InvokeOnDone(quota_error_flag);

            return(max_messages_per_session);
        }
コード例 #20
0
ファイル: ad.cs プロジェクト: zhamppx97/dotnet-api-docs
// </Snippet4>

    public static void Main()
    {
        int result;
        int param;

// <Snippet6>
        // Creates an instance of a context-bound type SampleSynchronized.
        SampleSynchronized sampSyncObj = new SampleSynchronized();

        // Checks whether the object is a proxy, since it is context-bound.
        if (RemotingServices.IsTransparentProxy(sampSyncObj))
        {
            Console.WriteLine("sampSyncObj is a proxy.");
        }
        else
        {
            Console.WriteLine("sampSyncObj is NOT a proxy.");
        }
// </Snippet6>
// <Snippet7>

        param = 10;

        Console.WriteLine("");
        Console.WriteLine("Making a synchronous call on the context-bound object:");

        result = sampSyncObj.Square(param);
        Console.Write("The result of calling sampSyncObj.Square with ");
        Console.WriteLine("{0} is {1}.", param, result);
        Console.WriteLine("");

// </Snippet7>
// <Snippet8>
        SampSyncSqrDelegate sampleDelegate = new SampSyncSqrDelegate(sampSyncObj.Square);

        param = 8;

        Console.WriteLine("Making a single asynchronous call on the context-bound object:");

        IAsyncResult ar1 = sampleDelegate.BeginInvoke(param,
                                                      new AsyncCallback(AsyncResultSample.MyCallback),
                                                      param);

        Console.WriteLine("Waiting for the asynchronous call to complete...");
        WaitHandle wh = ar1.AsyncWaitHandle;

        wh.WaitOne();

        wh.Close();

        Console.WriteLine("");
        Console.WriteLine("Waiting for the AsyncCallback to complete...");
        // Note that normally, a callback and a wait handle would not
        // both be used on the same asynchronous call. Callbacks are
        // useful in cases where the original thread does not need to
        // be synchronized with the result of the call, and in that
        // scenario they provide a place to call EndInvoke. Sleep is
        // used here because the callback is on a ThreadPool thread.
        // ThreadPool threads are background threads, and will not keep
        // a process running when the main thread ends.
        Thread.Sleep(1000);
// </Snippet8>
    }
コード例 #21
0
        /// <inheritdoc />
        public ProcessRunResults RunProcess(
            string fileName,
            string arguments,
            Dictionary <string, string> environmentVars,
            WaitHandle cancelWaitHandle,
            bool shouldIgnoreConsoleOutput,
            IEnumerable <int> successfulExitCodes,
            long maxWorkingSetSizeMb       = 0,
            string processWorkingDirectory = null,
            int maxAllowedRuntimeInMinutes = 0,
            long maxVirtualMemorySizeMb    = 0,
            IProgress <string> progress    = null,
            string processKillDumpFile     = null)
        {
            _log.LogDebug("Running Process: fileName({0}) arguments({1})", fileName, arguments);

            // Check for cancel before we go through the work of launching the process.
            if (cancelWaitHandle != null && cancelWaitHandle.WaitOne(0))
            {
                throw new OperationCanceledException();
            }

            if (environmentVars != null)
            {
                foreach (var envVars in environmentVars)
                {
                    _log.LogDebug("{0} : {1}", envVars.Key, envVars.Value);
                }
            }

            if (successfulExitCodes == null)
            {
                successfulExitCodes = new int[]
                {
                    0,
                };
            }

            using (var helper = new ProcessHelper(
                       _log,
                       fileName,
                       arguments,
                       environmentVars,
                       cancelWaitHandle,
                       shouldIgnoreConsoleOutput,
                       maxWorkingSetSizeMb,
                       processWorkingDirectory,
                       maxAllowedRuntimeInMinutes,
                       maxVirtualMemorySizeMb,
                       progress,
                       processKillDumpFile))
            {
                AddChildProcess(helper);
                try
                {
                    helper.Run();

                    if (new HashSet <int>(successfulExitCodes).Contains(helper.ExitCode))
                    {
                        // exit code was successful
                        return(new ProcessRunResults(helper.StandardOutput, helper.StandardError));
                    }

                    _log.LogDebug("Running Process Failed: fileName({0}) arguments({1}) exitCode({2})", fileName, arguments, helper.ExitCode);
                    _log.LogDebug("StdOut: {0}", helper.StandardOutput);
                    _log.LogDebug("StdErr: {0}", helper.StandardError);

                    throw new ProcessRunException(fileName, arguments, helper.ExitCode, helper.StandardOutput, helper.StandardError);
                }
                finally
                {
                    RemoveChildProcess(helper);
                }
            }
        }
コード例 #22
0
        /// <summary>
        /// Create socket with connection timeout.
        /// </summary>
        public Connection(IPEndPoint address, int timeoutMillis, int maxSocketIdleMillis, Pool pool)
        {
            this.maxSocketIdleMillis = (double)(maxSocketIdleMillis);
            this.pool = pool;

            try
            {
                socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            }
            catch (Exception e)
            {
                throw new AerospikeException.Connection(e);
            }

            try
            {
                socket.NoDelay = true;

                if (timeoutMillis > 0)
                {
                    socket.SendTimeout    = timeoutMillis;
                    socket.ReceiveTimeout = timeoutMillis;
                }
                else
                {
                    // Never allow timeoutMillis of zero (no timeout) because WaitOne returns
                    // immediately when that happens!
                    // Retry functionality will attempt to reconnect later.
                    timeoutMillis = 2000;
                }

#if NETFRAMEWORK
                IAsyncResult result = socket.BeginConnect(address, null, null);
                WaitHandle   wait   = result.AsyncWaitHandle;

                if (wait.WaitOne(timeoutMillis))
                {
                    // Connection succeeded.
                    // EndConnect will automatically close AsyncWaitHandle.
                    socket.EndConnect(result);
                }
                else
                {
                    // Connection timed out.
                    // Do not close AsyncWaitHandle. If AsyncWaitHandle is closed,
                    // the disposed handle can be referenced after the timeout exception is thrown.
                    // The handle will eventually get closed by the garbage collector.
                    // See: https://social.msdn.microsoft.com/Forums/en-US/313cf28c-2a6d-498e-8188-7a0639dbd552/tcpclientbeginconnect-issue?forum=netfxnetcom
                    throw new SocketException((int)SocketError.TimedOut);
                }
#else
                System.Threading.Tasks.Task task = socket.ConnectAsync(address);

                if (!task.Wait(timeoutMillis))
                {
                    // Connection timed out.
                    throw new SocketException((int)SocketError.TimedOut);
                }
#endif
                timestamp = DateTime.UtcNow;
            }
            catch (Exception e)
            {
                //socket.Close();
                socket.Dispose();
                throw new AerospikeException.Connection(e);
            }
        }
コード例 #23
0
        /// <summary>
        /// Asserts that the given handle will be signaled within the default timeout.
        /// </summary>
        public static void ExpectEvent(WaitHandle eventOccurred, string eventName_NoRetry)
        {
            string message = String.Format("Didn't observe a {0} event within {1}ms", eventName_NoRetry, WaitForExpectedEventTimeout_NoRetry);

            Assert.True(eventOccurred.WaitOne(WaitForExpectedEventTimeout_NoRetry), message);
        }
コード例 #24
0
        public static Task <bool> ToTask(this WaitHandle handle, int timeout = Timeout.Infinite, CancellationToken cancellationToken = default(CancellationToken))
        {
            Requires.NotNull(handle, nameof(handle));

            // Check whether the handle is already signaled as an optimization.
            // But even for WaitOne(0) the CLR can pump messages if called on the UI thread, which the caller may not
            // be expecting at this time, so be sure there is no message pump active by controlling the SynchronizationContext.
            using (NoMessagePumpSyncContext.Default.Apply())
            {
                if (handle.WaitOne(0))
                {
                    return(TrueTask);
                }
                else if (timeout == 0)
                {
                    return(FalseTask);
                }
            }

            cancellationToken.ThrowIfCancellationRequested();
            var tcs = new TaskCompletionSource <bool>();

            // Arrange that if the caller signals their cancellation token that we complete the task
            // we return immediately. Because of the continuation we've scheduled on that task, this
            // will automatically release the wait handle notification as well.
            CancellationTokenRegistration cancellationRegistration =
                cancellationToken.Register(
                    state =>
            {
                var tuple = (Tuple <TaskCompletionSource <bool>, CancellationToken>)state;
                tuple.Item1.TrySetCanceled(tuple.Item2);
            },
                    Tuple.Create(tcs, cancellationToken));

            RegisteredWaitHandle callbackHandle = ThreadPool.RegisterWaitForSingleObject(
                handle,
                (state, timedOut) => ((TaskCompletionSource <bool>)state).TrySetResult(!timedOut),
                state: tcs,
                millisecondsTimeOutInterval: timeout,
                executeOnlyOnce: true);

            // It's important that we guarantee that when the returned task completes (whether cancelled, timed out, or signaled)
            // that we release all resources.
            if (cancellationToken.CanBeCanceled)
            {
                // We have a cancellation token registration and a wait handle registration to release.
                // Use a tuple as a state object to avoid allocating delegates and closures each time this method is called.
                tcs.Task.ContinueWith(
                    (_, state) =>
                {
                    var tuple = (Tuple <RegisteredWaitHandle, CancellationTokenRegistration>)state;
                    tuple.Item1.Unregister(null); // release resources for the async callback
                    tuple.Item2.Dispose();        // release memory for cancellation token registration
                },
                    Tuple.Create <RegisteredWaitHandle, CancellationTokenRegistration>(callbackHandle, cancellationRegistration),
                    CancellationToken.None,
                    TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default);
            }
            else
            {
                // Since the cancellation token was the default one, the only thing we need to track is clearing the RegisteredWaitHandle,
                // so do this such that we allocate as few objects as possible.
                tcs.Task.ContinueWith(
                    (_, state) => ((RegisteredWaitHandle)state).Unregister(null),
                    callbackHandle,
                    CancellationToken.None,
                    TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default);
            }

            return(tcs.Task);
        }
コード例 #25
0
        /// <summary>
        /// build thread and process list periodically and fire update event and enqueue results for the socket thread
        /// </summary>
        void usageThread()
        {
            try
            {
                int interval = 3000;

                uint start = Process.GetTickCount();
                Dictionary <uint, thread> old_thread_List;// = Process.GetThreadList();

                string exeFile = Process.exefile;
                //read all processes
                Dictionary <uint, process> ProcList = Process.getProcessNameList();
                DateTime dtCurrent = DateTime.Now;

                //######### var declarations
                Dictionary <uint, thread> new_ThreadList;
                uint  duration;
                long  system_total;
                long  user_total, kernel_total;     //total process spend in user/kernel
                long  thread_user, thread_kernel;   //times the thread spend in user/kernel
                DWORD dwProc;
                float user_percent;
                float kernel_percent;
                ProcessStatistics.process_usage      usage;
                ProcessStatistics.process_statistics stats = null;

                string        sProcessName      = "";
                List <thread> processThreadList = new List <thread>();

                //extended list
                List <threadStatistic> processThreadStatsList = new List <threadStatistic>(); //to store thread stats
                //threadtimes threadTimesTotal;
                while (!bStopMainThread)
                {
                    eventEnableCapture.WaitOne();
                    old_thread_List = Process.GetThreadList();  //build a list of threads with user and kernel times

                    System.Threading.Thread.Sleep(interval);

                    //get a new thread list
                    new_ThreadList = Process.GetThreadList();   //build another list of threads with user and kernel times, to compare

                    duration = Process.GetTickCount() - start;

                    ProcList     = Process.getProcessNameList(); //update process list
                    dtCurrent    = DateTime.Now;
                    system_total = 0;
                    statisticsTimes.Clear();
                    //look thru all processes
                    foreach (KeyValuePair <uint, process> p2 in ProcList)
                    {
                        //empty the process's thread list
                        processThreadList      = new List <thread>();
                        processThreadStatsList = new List <threadStatistic>();

                        user_total   = 0;    //hold sum of thread user times for a process
                        kernel_total = 0;    //hold sum of thread kernel times for a process
                        sProcessName = p2.Value.sName;

                        //SUM over all threads with that ProcID
                        dwProc = p2.Value.dwProcID;
                        foreach (KeyValuePair <uint, thread> kpNew in new_ThreadList)
                        {
                            thread_user   = 0;
                            thread_kernel = 0;
                            //if the thread belongs to the process
                            if (kpNew.Value.dwOwnerProcID == dwProc)
                            {
                                //is there an old thread entry we can use to calc?
                                thread threadOld;
                                if (old_thread_List.TryGetValue(kpNew.Value.dwThreadID, out threadOld))
                                {
                                    thread_user   = Process.GetThreadTick(kpNew.Value.thread_times.user) - Process.GetThreadTick(old_thread_List[kpNew.Value.dwThreadID].thread_times.user);
                                    user_total   += thread_user;
                                    thread_kernel = Process.GetThreadTick(kpNew.Value.thread_times.kernel) - Process.GetThreadTick(old_thread_List[kpNew.Value.dwThreadID].thread_times.kernel);
                                    kernel_total += thread_kernel;
                                }
                                //simple list
                                thread threadsOfProcess = new thread(kpNew.Value.dwOwnerProcID, kpNew.Value.dwThreadID, kpNew.Value.thread_times);
                                processThreadList.Add(threadsOfProcess);

                                //extended list
                                threadStatistic threadStats =
                                    new threadStatistic(
                                        kpNew.Value.dwOwnerProcID,
                                        kpNew.Value.dwThreadID,
                                        new threadtimes(thread_user, thread_kernel),
                                        duration,
                                        dtCurrent.Ticks);
                                processThreadStatsList.Add(threadStats);
                            }//if dwProcID matches
                        }
                        //end of sum for process
                        user_percent   = (float)user_total / (float)duration * 100f;
                        kernel_percent = (float)kernel_total / (float)duration * 100f;
                        system_total   = user_total + kernel_total;

                        // update the statistics with this process' info
                        usage = new ProcessStatistics.process_usage(kernel_total, user_total);
                        // update process statistics
                        //stats = new ProcessStatistics.process_statistics(p2.Value.dwProcID, p2.Value.sName, usage, dtCurrent.Ticks, duration, processThreadList);
                        stats = new ProcessStatistics.process_statistics(p2.Value.dwProcID, p2.Value.sName, usage, dtCurrent.Ticks, duration, processThreadStatsList);

                        //add or update the proc stats
                        if (exeFile != p2.Value.sName || bIncludeMySelf)
                        {
                            //if (sProcessName == "device.exe")
                            //    System.Diagnostics.Debug.WriteLine(stats.ToString());

                            statisticsTimes[p2.Value.sName] = stats;
                            //lock (lockQueue)
                            //{
                            //System.Diagnostics.Debug.WriteLine("Queue Adding " + stats.sName);
                            //procStatsQueue.Enqueue(stats);
                            procStatsQueueBytes.Enqueue(stats.ToByte());
                            //}
                        }

                        start = Process.GetTickCount();
                    }//foreach process

                    onUpdateHandler(new ProcessStatsEventArgs(statisticsTimes, duration));
                    procStatsQueueBytes.Enqueue(ByteHelper.endOfTransferBytes);
                    ((AutoResetEvent)eventEnableSend).Set();
                    //dumpStatistics(statisticsTimes);
                }//while true
            }
            catch (ThreadAbortException ex)
            {
                System.Diagnostics.Debug.WriteLine("ThreadAbortException: usageThread(): " + ex.Message);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception: usageThread(): " + ex.Message);
            }
            System.Diagnostics.Debug.WriteLine("Thread ENDED");
        }
コード例 #26
0
 void Wait(WaitHandle handle)
 {
     Assert.IsTrue(handle.WaitOne(5000, true), "WaitHandle did not trigger");
 }
コード例 #27
0
 /// <summary>
 /// Waits for user input and hides dialog once ready
 /// </summary>
 /// <returns>Current value of DialogResult</returns>
 private bool WaitAndHide()
 {
     WaitHandle.WaitOne();
     HideDialog?.Invoke(this);
     return(DialogResult);
 }
コード例 #28
0
    public static bool WaitOne(WaitHandle handle, int timeoutInMs)
    {
        string strDatetimeFormat = "HH:mm:ss.fff";

        Console.WriteLine("Wait Entry");
        Console.WriteLine("Wait Timeout : {0} ", timeoutInMs);
        Console.WriteLine("Wait Start : {0}", DateTime.Now.ToString(strDatetimeFormat));

        TimeSpan timeout = new TimeSpan(0, 0, 0, 0, timeoutInMs);

        int  expireTicks = 0, waitTime = 0;;
        bool signaled = false, exitLoop = false;

        #region Check The Inputs...
        if (handle == null)
        {
            throw new ArgumentException("handle is null");
        }
        else if ((handle.SafeWaitHandle.IsClosed))
        {
            throw new ArgumentException("closed wait handle", "handle");
        }
        else if ((handle.SafeWaitHandle.IsInvalid))
        {
            throw new ArgumentException("invalid wait handle", "handle");
        }
        else if ((timeout < WaitOneDefiniton.InfiniteTimeout))
        {
            throw new ArgumentException("invalid timeout < -1", "timeout");
        }

        #endregion

        #region Wait For The Signal...
        expireTicks = (int)Environment.TickCount + (int)timeout.TotalMilliseconds;

        do
        {
            if (timeout.Equals(WaitOneDefiniton.InfiniteTimeout))
            {
                waitTime = WaitOneDefiniton.MaxWait;
            }
            else
            {
                waitTime = (expireTicks - Environment.TickCount);
                if (waitTime <= 0)
                {
                    exitLoop = true;
                    waitTime = 0;
                }
                else if (waitTime > WaitOneDefiniton.MaxWait)
                {
                    waitTime = WaitOneDefiniton.MaxWait;
                }
            }

            if ((handle.SafeWaitHandle.IsClosed))
            {
                exitLoop = true;
            }
            else if (handle.WaitOne(waitTime, false))
            {
                exitLoop = true;
                signaled = true;
            }
            else
            {
                if (Application.MessageLoop)
                {
                    Application.DoEvents();
                }
                else
                {
                    Thread.Sleep(1);
                }
            }
        }while (!exitLoop);

        #endregion

        Console.WriteLine("Wait End : {0}", DateTime.Now.ToString(strDatetimeFormat));
        Console.WriteLine("Wait Return Object : Signaled ({0})", signaled.ToString());

        Console.WriteLine("Wait Exit");
        return(signaled);
    }
コード例 #29
0
    // this one just tests that WaitOne will receive an
    // ObjectDisposedException if the Mutex is disposed of
    // by the spawned thread while WaitOne is waiting on it
    public bool NegTest2()
    {
        bool retVal = false;
        Thread thread = null;

        TestLibrary.TestFramework.BeginScenario("NegTest2: ObjectDisposedException should be thrown if current instance has already been disposed");

        try
        {
            // m_Handle is of type WaitHandle
            // Mutex is a subclass of WaitHandle
            m_Handle = new Mutex();

            // Spin up a thread.  DisposeMutex
            // simply tries to dispose of the mutex.
            thread = new Thread(new ThreadStart(DisposeMutex));
            // Start it
            thread.Start();
            Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race
            Thread.Sleep(c_DEFAULT_SLEEP_TIME);
            // Now, the spawned thread should have 
            // had plenty of time to dispose of the mutex
            // Calling WaitOne at this point should result
            // in an ObjectDisposedException being thrown
            m_Handle.WaitOne();

            // We should not get here
            TestLibrary.TestFramework.LogError("103", "ObjectDisposedException is not thrown if current instance has already been disposed");
            retVal = false;
        }
        catch (ObjectDisposedException)
        {
            // Swallow it, this is where we want
            // the test to go
            retVal = true;
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }
        finally
        {
            if (null != thread)
            {
                // Wait for the spawned thread to finish
                // cleaning up
                thread.Join();
            }

            if (null != m_Handle)
            {
                // spawned thread was unable to dispose of it
                ((IDisposable)m_Handle).Dispose();
            }
        }

        return retVal;
    }
コード例 #30
0
ファイル: PipeStream.Windows.cs プロジェクト: yicong/corefx
        private unsafe int EndRead(IAsyncResult asyncResult)
        {
            // There are 3 significantly different IAsyncResults we'll accept
            // here.  One is from Stream::BeginRead.  The other two are variations
            // on our PipeStreamAsyncResult.  One is from BeginReadCore,
            // while the other is from the BeginRead buffering wrapper.
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }
            if (!_isAsync)
            {
                return(_streamAsyncHelper.EndRead(asyncResult));
            }

            PipeStreamAsyncResult afsar = asyncResult as PipeStreamAsyncResult;

            if (afsar == null || afsar._isWrite)
            {
                throw __Error.GetWrongAsyncResult();
            }

            // Ensure we can't get into any races by doing an interlocked
            // CompareExchange here.  Avoids corrupting memory via freeing the
            // NativeOverlapped class or GCHandle twice.
            if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
            {
                throw __Error.GetEndReadCalledTwice();
            }

            ReadWriteAsyncParams readWriteParams    = asyncResult.AsyncState as ReadWriteAsyncParams;
            IOCancellationHelper cancellationHelper = null;

            if (readWriteParams != null)
            {
                cancellationHelper = readWriteParams.CancellationHelper;
                if (cancellationHelper != null)
                {
                    readWriteParams.CancellationHelper.SetOperationCompleted();
                }
            }

            // Obtain the WaitHandle, but don't use public property in case we
            // delay initialize the manual reset event in the future.
            WaitHandle wh = afsar._waitHandle;

            if (wh != null)
            {
                // We must block to ensure that AsyncPSCallback has completed,
                // and we should close the WaitHandle in here.  AsyncPSCallback
                // and the hand-ported imitation version in COMThreadPool.cpp
                // are the only places that set this event.
                using (wh)
                {
                    wh.WaitOne();
                    Debug.Assert(afsar._isComplete == true,
                                 "FileStream::EndRead - AsyncPSCallback didn't set _isComplete to true!");
                }
            }

            // Free memory & GC handles.
            NativeOverlapped *overlappedPtr = afsar._overlapped;

            if (overlappedPtr != null)
            {
                Overlapped.Free(overlappedPtr);
            }

            // Now check for any error during the read.
            if (afsar._errorCode != 0)
            {
                if (afsar._errorCode == Interop.ERROR_OPERATION_ABORTED)
                {
                    if (cancellationHelper != null)
                    {
                        cancellationHelper.ThrowIOOperationAborted();
                    }
                }
                WinIOError(afsar._errorCode);
            }

            // set message complete to true if the pipe is broken as well; need this to signal to readers
            // to stop reading
            _isMessageComplete = _state == PipeState.Broken ||
                                 afsar._isMessageComplete;

            return(afsar._numBytes);
        }
コード例 #31
0
 /// <summary>
 /// Blocks the current thread until the current <see cref="T:System.Threading.WaitHandle"/> receives a signal, while observing a <see cref="T:System.Threading.CancellationToken"/>.
 /// </summary>
 /// <param name="waitHandle">The wait handle to wait on</param>
 /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to observe.</param>
 /// <exception cref="T:System.InvalidOperationException">The maximum number of waiters has been exceeded.</exception>
 /// <exception cref="T:System.OperationCanceledExcepton"><paramref name="cancellationToken"/> was canceled.</exception>
 /// <exception cref="T:System.ObjectDisposedException">The object has already been disposed or the <see cref="T:System.Threading.CancellationTokenSource"/> that created <paramref name="cancellationToken"/> has been disposed.</exception>
 public static bool WaitOne(this WaitHandle waitHandle, CancellationToken cancellationToken)
 {
     return(waitHandle.WaitOne(Timeout.Infinite, cancellationToken));
 }
コード例 #32
0
ファイル: PipeStream.Windows.cs プロジェクト: yicong/corefx
        private unsafe void EndWrite(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            if (!_isAsync)
            {
                _streamAsyncHelper.EndWrite(asyncResult);
                return;
            }

            PipeStreamAsyncResult afsar = asyncResult as PipeStreamAsyncResult;

            if (afsar == null || !afsar._isWrite)
            {
                throw __Error.GetWrongAsyncResult();
            }

            // Ensure we can't get into any races by doing an interlocked
            // CompareExchange here.  Avoids corrupting memory via freeing the
            // NativeOverlapped class or GCHandle twice.  --
            if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
            {
                throw __Error.GetEndWriteCalledTwice();
            }

            ReadWriteAsyncParams readWriteParams    = afsar.AsyncState as ReadWriteAsyncParams;
            IOCancellationHelper cancellationHelper = null;

            if (readWriteParams != null)
            {
                cancellationHelper = readWriteParams.CancellationHelper;
                if (cancellationHelper != null)
                {
                    cancellationHelper.SetOperationCompleted();
                }
            }

            // Obtain the WaitHandle, but don't use public property in case we
            // delay initialize the manual reset event in the future.
            WaitHandle wh = afsar._waitHandle;

            if (wh != null)
            {
                // We must block to ensure that AsyncPSCallback has completed,
                // and we should close the WaitHandle in here.  AsyncPSCallback
                // and the hand-ported imitation version in COMThreadPool.cpp
                // are the only places that set this event.
                using (wh)
                {
                    wh.WaitOne();
                    Debug.Assert(afsar._isComplete == true, "PipeStream::EndWrite - AsyncPSCallback didn't set _isComplete to true!");
                }
            }

            // Free memory & GC handles.
            NativeOverlapped *overlappedPtr = afsar._overlapped;

            if (overlappedPtr != null)
            {
                Overlapped.Free(overlappedPtr);
            }

            // Now check for any error during the write.
            if (afsar._errorCode != 0)
            {
                if (afsar._errorCode == Interop.ERROR_OPERATION_ABORTED)
                {
                    if (cancellationHelper != null)
                    {
                        cancellationHelper.ThrowIOOperationAborted();
                    }
                }
                WinIOError(afsar._errorCode);
            }

            // Number of buffer written is afsar._numBytes.
            return;
        }
コード例 #33
0
 private static void Wait(WaitHandle handle)
 {
     Assert.IsTrue(handle.WaitOne(1000000, true), "Wait handle failed to trigger");
 }
        /// <summary>
        /// Handles the 'magic' of safely invoking the delegate on the control without producing
        /// a dead-lock.
        /// </summary>
        public void EventHandler(object sender, TEventArgs args)
        {
            bool requiresInvoke = false, hasHandle = false;

            try
            {
                lock (_control)                 // locked to avoid conflicts with RecreateHandle and DestroyHandle
                {
                    if (true == (hasHandle = _control.IsHandleCreated))
                    {
                        requiresInvoke = _control.InvokeRequired;
                        // must remain true for InvokeRequired to be dependable
                        hasHandle &= _control.IsHandleCreated;
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                requiresInvoke = hasHandle = false;
            }

            if (!requiresInvoke && hasHandle)             // control is from the current thread
            {
                _delegate(sender, args);
                return;
            }
            else if (hasHandle)             // control invoke *might* work
            {
                MethodInvokerImpl invocation = new MethodInvokerImpl(_delegate, sender, args);
                IAsyncResult      result     = null;
                try
                {
                    lock (_control)                    // locked to avoid conflicts with RecreateHandle and DestroyHandle
                        result = _control.BeginInvoke(invocation.Invoker);
                }
                catch (InvalidOperationException)
                { }

                try
                {
                    if (result != null)
                    {
                        WaitHandle handle   = result.AsyncWaitHandle;
                        TimeSpan   interval = TimeSpan.FromSeconds(1);
                        bool       complete = false;

                        while (!complete && (invocation.MethodRunning || IsControlValid(_control)))
                        {
                            if (invocation.MethodRunning)
                            {
                                complete = handle.WaitOne();                                //no need to continue polling once running
                            }
                            else
                            {
                                complete = handle.WaitOne(interval, false);
                            }
                        }

                        if (complete)
                        {
                            _control.EndInvoke(result);
                            return;
                        }
                    }
                }
                catch (ObjectDisposedException ode)
                {
                    if (ode.ObjectName != _control.GetType().Name)
                    {
                        throw;                        // *likely* from some other source...
                    }
                }
            }

            OnControlDisposed(sender, args);
        }
コード例 #35
0
ファイル: Utility.cs プロジェクト: wollnyst/corefx
 public static void ExpectNoEvent(WaitHandle eventOccured, string eventName, int timeout = Utility.Timeout)
 {
     string message = String.Format("Should not observe a {0} event", eventName);
     Assert.False(eventOccured.WaitOne(timeout), message);
 }
コード例 #36
0
 public static void turnRight(double graden, SByte speed, Boolean brake, Boolean silent)
 {
     //Init vehicle, waitHandle en speaker
     //Turning ..graden to the left
     LcdConsole.WriteLine ("Turning " + graden + " degrees right");
     //Convert degrees to cm. Bereken eerst de graad/Cm en vul deze in bij de constanten
     uint gradencorrect = (uint)(graden * graadCmTurn); //Want graden * graadCm geeft de precieze draai.
     //Hier begint de magie
     waitHandle = vehicle.SpinRight(speed,gradencorrect,brake);
     //Geef die motor even rust
     waitHandle.WaitOne();
     LcdConsole.WriteLine ("Done turning right!");
     if (!silent) {
         speaker.Buzz ();
     }
     Thread.Sleep (100);
 }
コード例 #37
0
ファイル: Utility.cs プロジェクト: noahfalk/corefx
 public static void ExpectEvent(WaitHandle eventOccurred, string eventName, int timeout = WaitForExpectedEventTimeout)
 {
     string message = String.Format("Didn't observe a {0} event within {1}ms", eventName, timeout);
     Assert.True(eventOccurred.WaitOne(timeout), message);
 }
コード例 #38
0
ファイル: VForm.cs プロジェクト: windrobin/kumpro
            public UTRes UploadThem(String[] alfp, Uri baseUri)
            {
                foreach (String fp in alfp)
                {
                    if (cancel.WaitOne(0, false))
                    {
                        return(UTRes.Cancel);
                    }
                    Uri uriTo = UUt.CombineFile(baseUri, Path.GetFileName(fp));
                    using (HeadRes head = DInfo.Head(uriTo, conn)) {
                        head.Dispose();
                        if (0 == (File.GetAttributes(fp) & FileAttributes.Directory))
                        {
                            if (head.Exists)
                            {
                                switch (QueryOvwr(head.baseUri.ToString()))
                                {
                                case DialogResult.Yes:
                                    break;

                                case DialogResult.No:
                                    continue;

                                case DialogResult.Cancel:
                                    return(UTRes.Cancel);
                                }
                            }
                            head.Dispose();
                            using (GenRes uploaded = DInfo.Upload2(uriTo, fp, conn, nio, cancel)) {
                                if (cancel.WaitOne(0, true))
                                {
                                    using (GenRes rest = DInfo.Delete(uriTo, conn)) {
                                    }
                                }
                            }
                            using (GenRes set = DInfo.SetMt(uriTo, fp, conn)) {
                            }
                        }
                        else
                        {
                            Uri uriDir = UUt.CombineFile(baseUri, Path.GetFileName(fp));

                            if (!head.Exists)
                            {
                                using (GenRes newf = DInfo.NewFolder(uriTo, conn)) {
                                    if (!newf.Success)
                                    {
                                        continue;
                                    }
                                }
                            }

                            switch (UploadThem(Directory.GetFileSystemEntries(fp), uriDir))
                            {
                            case UTRes.Cancel:
                                return(UTRes.Cancel);
                            }
                        }
                    }
                }
                return(UTRes.Ok);
            }
コード例 #39
0
        /// <summary>
        /// Start the client and establish a connection to the server.
        /// </summary>
        /// <returns></returns>
        public Task StartAsync()
        {
            _Client = new TcpClient();
            IAsyncResult asyncResult    = null;
            WaitHandle   waitHandle     = null;
            bool         connectSuccess = false;

            if (_Mode == Mode.Tcp)
            {
                #region TCP

                Log("Watson TCP client connecting to " + _ServerIp + ":" + _ServerPort);

                _Client.LingerState = new LingerOption(true, 0);
                asyncResult         = _Client.BeginConnect(_ServerIp, _ServerPort, null, null);
                waitHandle          = asyncResult.AsyncWaitHandle;

                try
                {
                    connectSuccess = waitHandle.WaitOne(TimeSpan.FromSeconds(_ConnectTimeoutSeconds), false);
                    if (!connectSuccess)
                    {
                        _Client.Close();
                        throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _ServerPort);
                    }

                    _Client.EndConnect(asyncResult);

                    _SourceIp   = ((IPEndPoint)_Client.Client.LocalEndPoint).Address.ToString();
                    _SourcePort = ((IPEndPoint)_Client.Client.LocalEndPoint).Port;
                    _TcpStream  = _Client.GetStream();
                    _SslStream  = null;

                    Connected = true;
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    waitHandle.Close();
                }

                #endregion TCP
            }
            else if (_Mode == Mode.Ssl)
            {
                #region SSL

                Log("Watson TCP client connecting with SSL to " + _ServerIp + ":" + _ServerPort);

                _Client.LingerState = new LingerOption(true, 0);
                asyncResult         = _Client.BeginConnect(_ServerIp, _ServerPort, null, null);
                waitHandle          = asyncResult.AsyncWaitHandle;

                try
                {
                    connectSuccess = waitHandle.WaitOne(TimeSpan.FromSeconds(_ConnectTimeoutSeconds), false);
                    if (!connectSuccess)
                    {
                        _Client.Close();
                        throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _ServerPort);
                    }

                    _Client.EndConnect(asyncResult);

                    _SourceIp   = ((IPEndPoint)_Client.Client.LocalEndPoint).Address.ToString();
                    _SourcePort = ((IPEndPoint)_Client.Client.LocalEndPoint).Port;

                    if (AcceptInvalidCertificates)
                    {
                        // accept invalid certs
                        _SslStream = new SslStream(_Client.GetStream(), false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        // do not accept invalid SSL certificates
                        _SslStream = new SslStream(_Client.GetStream(), false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertificateCollection, SslProtocols.Tls12, !AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }

                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }

                    if (MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }

                    Connected = true;
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    waitHandle.Close();
                }

                #endregion SSL
            }
            else
            {
                throw new ArgumentException("Unknown mode: " + _Mode.ToString());
            }

            if (ServerConnected != null)
            {
                Task serverConnected = Task.Run(() => ServerConnected());
            }

            return(DataReceiver());
        }
コード例 #40
0
        /// <summary>
        /// Shows the image of the specified <see cref="EntityClass"/> on the specified map
        /// locations, delaying the specified time for each step.</summary>
        /// <param name="entityClass">
        /// The <see cref="EntityClass"/> whose image to show.</param>
        /// <param name="sites">
        /// An <see cref="Array"/> containing the coordinates of each <see cref="Site"/> to show the
        /// image on.</param>
        /// <param name="move">
        /// <c>true</c> to smoothly move the image from one <see cref="Site"/> to the next, without
        /// pausing at the start or end of each movement; <c>false</c> to show the image on each
        /// <see cref="Site"/>, moving abruptly to the next.</param>
        /// <param name="delay">
        /// The duration, in milliseconds, for which the image is shown on each <see cref="Site"/>.
        /// If this argument is non-positive, a default value of 250 msec is assumed.</param>
        /// <param name="abortSignal">
        /// A <see cref="WaitHandle"/> to signal that all display actions should be aborted.</param>
        /// <exception cref="InvalidOperationException">
        /// <b>ShowImage</b> was called on the <see cref="DispatcherObject.Dispatcher"/> thread of
        /// the <see cref="MapViewControl"/>, rather than on a background thread.</exception>
        /// <remarks>
        /// Please refer to <see cref="Graphics.MapView.ShowImage"/> for details.</remarks>

        public void ShowImage(EntityClass entityClass, PointI[] sites,
                              bool move, int delay, WaitHandle abortSignal)
        {
            if (Dispatcher.CheckAccess())
            {
                ThrowHelper.ThrowInvalidOperationException(Tektosyne.Strings.ThreadForeground);
            }

            // silently ignore invalid state or arguments
            if (MapView.IsDisposed || entityClass == null || sites == null ||
                abortSignal == null || abortSignal.WaitOne(0, false))
            {
                return;
            }

            // check that all coordinates are valid
            for (int i = 0; i < sites.Length; i++)
            {
                if (!MapView.MapGrid.Contains(sites[i]))
                {
                    return;
                }
            }

            // moving drops last site
            int siteCount = sites.Length;

            if (move)
            {
                --siteCount;
            }
            if (siteCount <= 0)
            {
                return;
            }

            // default delay is 250 msec
            if (delay <= 0)
            {
                delay = 250;
            }

            // prevent interference by idle animation
            var manager = MapViewManager.Instance;

            manager.AnimationResponse = TimerResponse.Suspend;

            Image tile = null; int tileIndex = -1;

            Dispatcher.Invoke(delegate {
                // ensure map view is up-to-date
                Renderer.InvalidateVisual();

                // draw first frame of entity class
                MapView.DrawTileToBuffer(entityClass.FrameIndex);
                tile = new Image()
                {
                    Source = MapView.TileCopyBuffer
                };
            });

            // get distance between center and upper-left corner
            SizeD  elementSize = MapView.MapGrid.Element.Bounds.Size;
            double radiusX     = elementSize.Width / 2.0;
            double radiusY     = elementSize.Height / 2.0;

            for (int index = 0; index < siteCount; index++)
            {
                // get display location for current site
                PointD sourceCenter = MapView.SiteToView(sites[index]);
                PointD source       = new PointD(sourceCenter.X - radiusX, sourceCenter.Y - radiusY);

                // show animated move to next target, if any
                if (move && sites[index] != sites[index + 1])
                {
                    PointD targetCenter = MapView.SiteToView(sites[index + 1]);
                    PointD target       = new PointD(targetCenter.X - radiusX, targetCenter.Y - radiusY);

                    // move from source to target within specified delay
                    Duration duration      = new Duration(TimeSpan.FromMilliseconds(delay));
                    var      leftAnimation = new DoubleAnimation(source.X, target.X, duration);
                    var      topAnimation  = new DoubleAnimation(source.Y, target.Y, duration);
                    leftAnimation.Freeze(); topAnimation.Freeze();

                    Dispatcher.Invoke(delegate {
                        // add tile to canvas when first shown
                        if (tileIndex < 0)
                        {
                            tileIndex = MapCanvas.Children.Add(tile);
                        }

                        // animate both coordinates simultaneously
                        tile.BeginAnimation(Canvas.LeftProperty, leftAnimation);
                        tile.BeginAnimation(Canvas.TopProperty, topAnimation);
                    });
                }
                else
                {
                    Dispatcher.Invoke(delegate {
                        // add tile to canvas when first shown
                        if (tileIndex < 0)
                        {
                            tileIndex = MapCanvas.Children.Add(tile);
                        }

                        // show image tile on current site
                        Canvas.SetLeft(tile, source.X);
                        Canvas.SetTop(tile, source.Y);
                    });
                }

                // wait for requested delay or abort signal
                if (abortSignal.WaitOne(delay, false))
                {
                    break;
                }
            }

            // allow idle animation but skip one tick
            manager.AnimationResponse = TimerResponse.SkipOne;

            // remove image tile when done (BeginInvoke avoids flickering)
            Dispatcher.BeginInvoke(delegate {
                if (tileIndex >= 0 && tileIndex < MapCanvas.Children.Count)
                {
                    MapCanvas.Children.RemoveAt(tileIndex);
                }
            });
        }
コード例 #41
0
ファイル: Utility.cs プロジェクト: noahfalk/corefx
 public static void ExpectNoEvent(WaitHandle eventOccurred, string eventName, int timeout = WaitForUnexpectedEventTimeout)
 {
     string message = String.Format("Should not observe a {0} event within {1}ms", eventName, timeout);
     Assert.False(eventOccurred.WaitOne(timeout), message);
 }
コード例 #42
0
ファイル: TimeoutHelper.cs プロジェクト: weshaggard/wcf
    public static bool WaitOne(WaitHandle waitHandle, TimeSpan timeout, bool exitSync)
    {
        if (timeout == TimeSpan.MaxValue)
        {
            waitHandle.WaitOne();
            return true;
        }
        else
        {
            TimeSpan maxWait = TimeSpan.FromMilliseconds(Int32.MaxValue);

            while (timeout > maxWait)
            {
                bool signaled = waitHandle.WaitOne(maxWait);

                if (signaled)
                {
                    return true;
                }

                timeout -= maxWait;
            }

            return waitHandle.WaitOne(timeout);
        }
    }