Exemplo n.º 1
0
 /// <summary>
 /// Shows the error state.
 /// </summary>
 /// <param name="error">
 /// The error message to display.
 /// </param>
 private void ShowError(string error)
 {
     ThreadExtensions.RunOnAppThread(() =>
     {
         errorText.text = error;
     });
 }
Exemplo n.º 2
0
        internal static void EnsureCatalogIsLoaded()
        {
            if (m_hasLoadedCatalog)
            {
                return;
            }

            bool gotLock = false;

            try {
                gotLock = Monitor.TryEnter(m_lockForCatalogLoad, TimeSpan.FromSeconds(20));
                if (!gotLock)
                {
                    string msg = StringExtensions.Fi("Thread '{0}' timed out while waiting on lock for loading the Syntax Catalog",
                                                     ThreadExtensions.GetDescription(Thread.CurrentThread));
                    throw new TimeoutException(msg);
                }

                if (m_hasLoadedCatalog)
                {
                    return;
                }

                SyntaxLoader.LoadCatalog();

                m_hasLoadedCatalog = true;
            } finally {
                if (gotLock)
                {
                    Monitor.Exit(m_lockForCatalogLoad);
                }
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// Shows the specified IPD.
 /// </summary>
 /// <param name="ipd">
 /// The IPD to show.
 /// </param>
 private void ShowIpd(float ipd)
 {
     ThreadExtensions.RunOnAppThread(() =>
     {
         ipdText.text = ipd.ToString();
     });
 }
Exemplo n.º 4
0
        private void TryConnect(EndPoint targetAddress)
        {
            var socketArgs = new SocketAsyncEventArgs {
                RemoteEndPoint = targetAddress
            };

            socketArgs.Completed += SocketConnectionComplete;
            nativeSocket.ConnectAsync(socketArgs);
            if (TimedOut != null)
            {
                ThreadExtensions.Start(() =>
                {
                    if (waitForTimeoutHandle.WaitOne((int)(Timeout * 1000)))
                    {
                        return;
                    }
                    if (IsConnected || isDisposed)
                    {
                        return;
                    }
                    TimedOut();
                    Dispose();
                });
            }
        }
Exemplo n.º 5
0
        public void EnqueueWorkerThreadTwoArgs()
        {
            const int Num1 = 1;
            const int Num2 = 2;

            ThreadExtensions.EnqueueWorkerThread(Num1, Num2,
                                                 (val1, val2) => { ValueSettingTestAction(val1, val2); });
        }
Exemplo n.º 6
0
        public void Start3()
        {
            const string Param = "name from parameter";
            Thread       t     = ThreadExtensions.Start(UpdateNameViaParameter, Param);

            t.Join();
            Assert.AreEqual(Param, t.Name);
        }
Exemplo n.º 7
0
        public void Start1()
        {
            int    num = 1;
            Thread t   = ThreadExtensions.Start(() => IncrementNumber(ref num));

            Assert.AreEqual(1, num);
            t.Join();
            Assert.AreEqual(2, num);
        }
Exemplo n.º 8
0
        public void Sleep_Demo()
        {
            ThreadExtensions.Sleep(500, true,
                                   () => Console.WriteLine($"This method is assync: {2000.Sleep()}"));
            500.Sleep(true);
            Console.WriteLine($"Returned from Sleep: {1000.Sleep()}");

            Console.WriteLine($"int: {float.MaxValue} {float.MaxValue.ToString().Length}");
            Console.WriteLine($"uint: {uint.MaxValue} {uint.MaxValue.ToString().Length}");
        }
        private void OnLaunchAppClicked(object launchButton, RoutedEventArgs e)
        {
            Panel   controlOwner = GetControlOwner(launchButton);
            AppInfo selectedApp  = GetBoundApp(controlOwner);

            (launchButton as Control).IsEnabled = false;
            Action enableLaunchButtonAgain =
                () => Dispatcher.BeginInvoke(new Action(() => (launchButton as Control).IsEnabled = true));

            ThreadExtensions.Start(() => LaunchApp(selectedApp, enableLaunchButtonAgain));
        }
Exemplo n.º 10
0
        public static void AbortAndFreeAll(this IThreadReference reference, int timeoutmSec = (int)Common.Extensions.TimeSpan.TimeSpanExtensions.MicrosecondsPerMillisecond)
        {
            foreach (var tp in reference.GetReferencedThreads())
            {
                //Take a reference to that thread
                System.Threading.Thread t = tp;

                //Call AbortAndFree                                                    //Should be Stopped to check for stop?
                if (false == ThreadExtensions.TryAbortAndFree(ref t, System.Threading.ThreadState.Running, timeoutmSec))
                {
                    t = null;                                                                                                      //Remove the reference if required
                }
            }
        }
Exemplo n.º 11
0
        public static void AbortAndFreeAll(this IThreadReference reference, System.TimeSpan timeout)
        {
            foreach (var tp in reference.GetReferencedThreads())
            {
                //Take a reference to that thread
                System.Threading.Thread t = tp;

                //Call AbortAndFree                                                    //Should be Stopped to check for stop?
                if (false == ThreadExtensions.TryAbortAndFree(ref t, timeout, System.Threading.ThreadState.Running))
                {
                    t = null;                                                                                                  //Remove the reference if required
                }
            }
        }
Exemplo n.º 12
0
 public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
 {
     if (ThreadExtensions.IsImpersonating())
     {
         _context.Push(() => {
             _logger.Log(logLevel, eventId, state, exception, formatter);
         });
     }
     else
     {
         _context.Flush();
         _logger.Log(logLevel, eventId, state, exception, formatter);
     }
 }
Exemplo n.º 13
0
        static void SetupStuff()
        {
            ThreadExtensions.Freeze(x => naps.Add(x));
            snapshots.RestoreSnapshots(repository, info).Returns(info2);
            disruptors.CreateJournalDisruptor(info2).Returns(journalDisruptor);
            disruptors.CreateSnapshotDisruptor().Returns(snapshotDisruptor);
            disruptors.CreateTransformationDisruptor(repository, info2).Returns(transformationDisruptor);
            messages.Restore(info2, journalDisruptor, repository).Returns(true);

            transformationDisruptor.RingBuffer.Returns(transformationRingBuffer);

            timeout.CreateSystemClock(transformationRingBuffer).Returns(systemClock);
            messaging.CreateMessageListener(transformationRingBuffer).Returns(listener);
        }
Exemplo n.º 14
0
        public void Sleep_Demo()
        {
            ThreadExtensions.Sleep(1, true);
            500.Sleep(true);
            750.Sleep(true);
            1000.Sleep(true);

            ThreadExtensions.Sleep(500, true,
                                   () => Console.WriteLine($"This method is assync: {2000.Sleep(true)}"));

            500.Sleep(true);

            Console.WriteLine($"Returned: {1000.Sleep(true)}");
        }
Exemplo n.º 15
0
        /// <summary>
        /// This thread will Send the Vidoe and tim to the clients every 5 seconds.
        /// </summary>
        private void CheckTime()
        {
            _started = DateTime.Now;
            while (!string.IsNullOrEmpty(_videoUrl))
            {
                IServer server = _player as IServer;
                if (server != null)
                {
                    server.SetVideo(_videoUrl);
                    TimeSpan elapsed = DateTime.Now - _started;
                    server.SeekVideo(elapsed.TotalSeconds);
                }

                ThreadExtensions.SaveSleep(5000);
            }
        }
Exemplo n.º 16
0
    private void UpdateVisualState()
    {
        ThreadExtensions.RunOnAppThread(() =>
        {
            switch (state)
            {
            case FBControllerState.LoggedIn:
                loggedInState.SetActive(true);
                break;

            default:
                loggedInState.SetActive(false);
                break;
            }
        });
    }
Exemplo n.º 17
0
        /// <summary>
        /// Updates the position of the song.
        /// </summary>
        private void UpdateTime()
        {
            while (!_disposing && _waveOutDevice != null && _currentSong != null && _playstream != null &&
                   (_waveOutDevice.PlaybackState == PlaybackState.Paused || _waveOutDevice.PlaybackState == PlaybackState.Playing))
            {
                try
                {
                    if (_waveOutDevice.PlaybackState == PlaybackState.Playing)
                    {
                        _currentSong.Position = Convert.ToInt64(_playstream.CurrentTime.TotalSeconds);
                        SongChanged?.Invoke(_currentSong);
                    }

                    ThreadExtensions.SaveSleep(1000);
                }
                catch
                {
                }
            }
        }
Exemplo n.º 18
0
        private async Task ReturnToMain(bool authenticated)
        {
            // Get our auth view
            var authView = AppViewManager.Views["Auth"];

            // Switch back to Main view and consolidate (close) this one
            await AppViewManager.Views["Main"].SwitchAsync(authView, ApplicationViewSwitchingOptions.ConsolidateViews);

            // Try to notify the controller but must do it on Unitys thread
            ThreadExtensions.RunOnAppThread(() =>
            {
                // Get our FB Controller
                var controller = GameObject.FindObjectOfType <FBController>();

                // If found, notify to continue
                if (controller != null)
                {
                    controller.ContinueAuthFromLogin((authenticated ? portal : null));
                }
            });
        }
Exemplo n.º 19
0
        private void InitSyntaxDefinition()
        {
            bool gotLock = Monitor.TryEnter(this, TimeSpan.FromSeconds(20));

            if (!gotLock)
            {
                string msg = StringExtensions.Fi("Thread {0} was waiting for the SyntaxDefinition for syntax '{1}' to be built by another thread, " +
                                                 "but after 20 seconds this is still not done. This may be due to excessive load on the computer or because of an Iris bug.",
                                                 ThreadExtensions.GetDescription(Thread.CurrentThread), this.Id);

                throw new TimeoutException(msg);
            }

            try {
                if (this.m_syntaxDefinition != null)
                {
                    return;
                }

                this.m_syntaxDefinition = SyntaxLoader.BuildSyntaxDefinition(this.Id);
            } finally {
                Monitor.Exit(this);
            }
        }
Exemplo n.º 20
0
        public static void Main(string[] args)
        {
            //if receiving a .mysquare url with token
            //register it
            if (args != null && args.Length == 1)
            {
                try
                {
                    string url = args[0];
                    if (url.StartsWith("mysquare:"))
                    {
                        url = url.Substring(9);
                        Configuration.Token = url;
                        MessageBox.Show("Your token was registered. Enjoy foursquare.", "MySquare");
                    }
                    else
                    {
                        throw new ApplicationException("Invalid token." + url);
                    }
                }
                catch (Exception ex)
                {
                    Log.RegisterLog(ex);
                    MessageBox.Show("An error occured while processing your token. Try again.", "MySquare");
                }
            }

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            using (UI.Main mainForm = new UI.Main())
            {
                try
                {
                    Configuration.CheckNotifications();
                    Network.CheckCacheFiles();

                    Location = new WorldPosition(true, Configuration.UseGps, 15000);
                    Location.LocationChanged += new EventHandler(Location_LocationChanged);
                    Location.PollHit         += new EventHandler(Location_PollHit);
                    Location.Poll();

                    Application.Run(mainForm);
                    ThreadExtensions.AbortThreads();
                    foreach (var obj in BaseController.Controllers)
                    {
                        try
                        {
                            obj.Service.Abort();
                        }
                        catch
                        { }
                    }

                    Configuration.abortCheck = true;
                    if (Configuration.PingInterval > 0)
                    {
                        Configuration.RetrievePings = (MessageBox.Show("Keep receiving check-in notifications after closing MySquare?", "MySquare", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes);
                    }
                }
                catch (ThreadAbortException) { }
                catch (ObjectDisposedException) { }
                catch (Exception ex)
                {
                    lastException = ex;
                    Service.Log.RegisterLog(ex);
                    Terminate();
                }
                finally
                {
                    DisposeThings();
                    if (lastException != null)
                    {
                        string message = "Unknown error: " + lastException.Message + "\r\n\r\nSorry for this inconvenience.";
#if DEBUG
                        message += "\r\n" + lastException.StackTrace;
#endif
                        MessageBox.Show(message, "MySquare", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    }
                }
                try
                {
                    mainForm.Close();
                    mainForm.Dispose();
                }
                catch (ObjectDisposedException) { }
            }
            Application.Exit();
        }
Exemplo n.º 21
0
 public void EnqueueWorkerThreadNoArgs()
 {
     Assert.IsTrue(ThreadExtensions.EnqueueWorkerThread(() => ValueSettingTestAction()));
 }
Exemplo n.º 22
0
        public void EnqueueWorkerThreadOneArg()
        {
            const int Num = 1;

            ThreadExtensions.EnqueueWorkerThread(Num, val => { ValueSettingTestAction(Num); });
        }
Exemplo n.º 23
0
        public void Start2()
        {
            Thread t = ThreadExtensions.Start("thread name", () => {});

            Assert.AreEqual("thread name", t.Name);
        }