private void OnFriendUpdate(FriendListUpdateDto update)
        {
            Friend friend;

            if (_friends.TryGetValue(update.ItemId, out friend))
            {
                friend.Status        = update.Data.Status;
                friend.Details       = update.Data.Details;
                friend.LastConnected = update.Data.LastConnected;
                friend.UserId        = update.Data.UserId;

                var action = FriendUpdated;
                if (action != null)
                {
                    MainThread.Post(() =>
                    {
                        action(friend);
                    });
                }
            }
            else
            {
                _logger.Log(Diagnostics.LogLevel.Warn, "friends.update", "Unknown friend with id " + update.ItemId);
            }
        }
        void PostEvent(ClientSessionEventKind eventKind)
        {
            var evnt = new ClientSessionEvent(this, eventKind);

            MainThread.Post(() => observable.Observers.OnNext(evnt));
            evnt.Post();
        }
        public void DismissMessage(int messageId)
        {
            MainThread.Post(() => {
                var messageIndex = messages.FindLastIndex(m => m.Id == messageId);
                if (messageIndex < 0)
                {
                    return;
                }

                var message = messages [messageIndex];

                messages = messages.RemoveAt(messageIndex);

                if (message.ShowSpinner)
                {
                    spinCount--;
                    if (spinCount == 0)
                    {
                        viewDelegate.StopSpinner();
                    }
                }

                if (messages.Count > 0)
                {
                    viewDelegate.DisplayMessage(messages [messages.Count - 1]);
                }
                else
                {
                    viewDelegate.DisplayIdle();
                }
            });
        }
Exemple #4
0
        void Terminate(AgentProcessState agentProcessState)
        {
            lock (runningAgentProcessStateLock) {
                agentProcessState.AgentProcess.UnexpectedlyTerminated
                    -= HandleAgentProcessUnexpectedlyTerminated;

                if (runningAgentProcessState == agentProcessState)
                {
                    runningAgentProcessState = null;
                }
            }

            AgentProcessTicket [] copiedTickets;
            lock (tickets) {
                copiedTickets = tickets.ToArray();
                tickets.Clear();
            }

            MainThread.Post(() => {
                foreach (var ticket in copiedTickets)
                {
                    try {
                        ticket.NotifyDisconnected();
                    } catch (Exception e) {
                        Log.Error(TAG, "exception when notifying ticket of disconnect", e);
                    }
                }
            });

            // Always run this as a form of disposal, because new AgentProcesses are created on-demand.
            // AgentProcess implementations should not let their Terminate implementations throw.
            agentProcessState.AgentProcess.TerminateAgentProcessAsync().Forget();
        }
Exemple #5
0
        void OnMouseHover(object sender, EventArgs e)
        {
            MainThread.Post(delegate(object x)
            {
                Point pt = PointToClient(MousePosition);
                if (_rcTitle != Rectangle.Empty && _rcTitle.Contains(pt))
                {
                    Graphics g = this.CreateGraphics();
                    SizeF size = g.MeasureString(_text, _titleBarFont);
                    _ttm.ShowSimpleToolTip(_text);
                    return;
                }

                if (_rcMinimize != Rectangle.Empty && _rcMinimize.Contains(pt))
                {
                    _ttm.ShowSimpleToolTip(Translator.Translate("TXT_BTNMINIMIZE"));
                    return;
                }

                if (_rcMaximize != Rectangle.Empty && _rcMaximize.Contains(pt))
                {
                    string tip = (WindowState != FormWindowState.Maximized) ?
                                 Translator.Translate("TXT_BTNMAXIMIZE") :
                                 Translator.Translate("TXT_BTNRESTOREDOWN");

                    _ttm.ShowSimpleToolTip(tip);
                    return;
                }

                if (_rcClose != Rectangle.Empty && _rcClose.Contains(pt))
                {
                    _ttm.ShowSimpleToolTip(Translator.Translate("TXT_BTNCLOSE"));
                }
            });
        }
        private void ConfirmScanAbortOnException(Exception ex)
        {
            if (ex is ThreadAbortException)
            {
                _abortScan.Set();
            }
            else
            {
                MainThread.Post(delegate(object x)
                {
                    string message = Translator.Translate("TXT_SCAN_ERROR_MSG", SourcePath, ex.Message);

                    TaskbarThumbnailManager.Instance.SetProgressStatus(TaskbarProgressBarStatus.Paused);

                    if (MessageDisplay.Query(message, "TXT_SCAN_ERROR", MessageBoxIcon.Exclamation) != DialogResult.Yes)
                    {
                        _abortScan.Set();
                    }
                    else
                    {
                        _abortScan.Reset();
                    }

                    TaskbarThumbnailManager.Instance.SetProgressStatus(TaskbarProgressBarStatus.Normal);
                });
            }
        }
 public void DispatchPacket(Packet packet)
 {
     if (this._asyncDispatch.Value)
     {
         Task.Factory.StartNew(() =>
         {
             try
             {
                 DispatchImpl(packet);
             }
             catch (Exception ex)
             {
                 MainThread.Post(() => UnityEngine.Debug.LogError(ex));
             }
         });
     }
     else
     {
         try
         {
             DispatchImpl(packet);
         }
         catch (Exception ex)
         {
             MainThread.Post(() => UnityEngine.Debug.LogError(ex));
         }
     }
 }
Exemple #8
0
        public async Task Post()
        {
            var e   = new ManualResetEventSlim(false);
            var tcs = new TaskCompletionSource <bool>();

            _mt.Post(o => {
                e.Wait();
                tcs.TrySetResult(true);
            }, null);

            tcs.Task.IsCompleted.Should().BeFalse();
            e.Set();
            await tcs.Task;

            tcs.Task.IsCompleted.Should().BeTrue();
        }
Exemple #9
0
 void OnStreamTitleChanged(Dictionary <string, string> data)
 {
     MainThread.Post((d) =>
     {
         SetTitle(mediaPlayer.BuildTitle());
     });
 }
        public Message PushMessage(Message message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            message = message.WithMessageService(this);

            MainThread.Post(() => {
                messages = messages.Add(message);

                if (message.ShowSpinner)
                {
                    spinCount++;
                    if (spinCount == 1)
                    {
                        viewDelegate.StartSpinner();
                    }
                }

                viewDelegate.DisplayMessage(message);
            });

            return(message);
        }
        void UpdateInstalledPackages()
        {
            sortedInstalledPackages = installedPackages
                                      .OrderBy(p => p.Identity.Id)
                                      .ToImmutableArray();

            MainThread.Post(() => NotifyPropertyChanged(nameof(InstalledPackages)));
        }
Exemple #12
0
 public void PublishEvaluation(
     CodeCellId codeCellid,
     object result,
     EvaluationResultHandling resultHandling = EvaluationResultHandling.Replace)
 => MainThread.Post(() => PublishEvaluation(new Evaluation {
     CodeCellId     = codeCellid,
     ResultHandling = resultHandling,
     Result         = RepresentationManager.Prepare(result)
 }));
 public void UpdateProgress(ulong completed, ulong total)
 {
     if (_taskbarList != null)
     {
         MainThread.Post(delegate(object x)
         {
             _taskbarList.SetProgressValue(MainThread.MainWindow.Handle, completed, total);
         });
     }
 }
 public void SetProgressStatus(TaskbarProgressBarStatus status)
 {
     if (_taskbarList != null)
     {
         MainThread.Post(delegate(object x)
         {
             _taskbarList.SetProgressState(MainThread.MainWindow.Handle, status);
         });
     }
 }
Exemple #15
0
        private void OnMessage(ChatMessageDto message)
        {
            OnUserUpdate(message.UserInfo);

            _messages.Enqueue(message);
            var action = OnChatMessage;

            if (action != null)
            {
                MainThread.Post(() => action(message));
            }
        }
Exemple #16
0
 //void _timer_Tick(object sender, EventArgs e)
 void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     try
     {
         _timer.Enabled = false;
         MainThread.Post((d) => DisplayNextFrame());
     }
     catch {}
     finally
     {
         _timer.Enabled = true;
     }
 }
Exemple #17
0
        public Message PushMessage(Message message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            message = message.WithMessageService(this);

            MainThread.Post(() => viewDelegate.DisplayMessage(message));

            return(message);
        }
 private void InvokeDisonnected(string reason)
 {
     if (_onDisconnected != null)
     {
         MainThread.Post(() =>
         {
             var action = _onDisconnected;
             if (action != null)
             {
                 action(reason);
             }
         });
     }
 }
        private void OnFriendAdd(FriendListUpdateDto update)
        {
            _friends[update.ItemId] = update.Data;

            var action = FriendAdded;

            if (action != null)
            {
                MainThread.Post(() =>
                {
                    action(update.Data);
                });
            }
        }
        private void PopulateAudioCDDrives()
        {
            cmbAudioCDDrives.Items.Clear();
            lvTracks.Items.Clear();

            DriveInfoItem selected = null;

            btnRefresh.Enabled = false;
            pbWaiting.Visible  = true;
            Application.DoEvents();

            ThreadPool.QueueUserWorkItem((c) =>
            {
                try
                {
                    DriveInfo[] audioCDs = CDDrive.GetAllAudioCDDrives();
                    foreach (DriveInfo di in audioCDs)
                    {
                        DriveInfoItem item = new DriveInfoItem(di);

                        MainThread.Post((d) => { cmbAudioCDDrives.Items.Add(item); });

                        if ((BkgTask as Task).DrivePath == null)
                        {
                            (BkgTask as Task).DrivePath = di.RootDirectory.FullName;
                        }

                        if (Path.Equals(di.RootDirectory.FullName, (BkgTask as Task).DrivePath))
                        {
                            selected = item;
                        }
                    }

                    MainThread.Post((d) =>
                    {
                        cmbAudioCDDrives.SelectedItem = selected;
                    });
                }
                finally
                {
                    MainThread.Post((d) =>
                    {
                        pbWaiting.Visible  = false;
                        btnRefresh.Enabled = true;
                    });
                }
            });
        }
Exemple #21
0
        protected void ShowWaitDialog(string message)
        {
            //if (InvokeRequired)
            //{
            //    Invoke(new ShowWaitDialogDG(ShowWaitDialog), message);
            //    return;
            //}

            MainThread.Post((d) =>
            {
                this.Enabled = false;
                CloseWaitDialog();
                _waitDialog = new GenericWaitDialog();
                _waitDialog.ShowDialog(message);
            });
        }
        protected virtual void OnAgentConnected()
        {
            ClientSession.Agent.Api.Messages.Subscribe(new Observer <object> (HandleAgentMessage));

            void HandleAgentMessage(object message)
            {
                if (message is CapturedOutputSegment segment)
                {
                    MainThread.Post(() => RenderCapturedOutputSegment(segment));
                }

                if (message is Evaluation result)
                {
                    MainThread.Post(() => RenderResult(result));
                }
            }
        }
Exemple #23
0
        void OnFileTaskProgress(ProgressEventType eventType, string file, UpdateProgressData data)
        {
            if (eventType == ProgressEventType.KeepAlive)
            {
                Application.DoEvents();
            }

            MainThread.Post(delegate(object x)
            {
                switch (eventType)
                {
                case ProgressEventType.Started:
                    pbOperation.Value   = 0;
                    pbOperation.Maximum = 10000;
                    pbOperation.Visible = (_task.ObjectsCount > 1);
                    TaskbarThumbnailManager.Instance.SetProgressStatus(TaskbarProgressBarStatus.Indeterminate);
                    TaskbarThumbnailManager.Instance.UpdateProgress(0, 10000);
                    break;

                case ProgressEventType.Aborted:
                    Close();
                    TaskbarThumbnailManager.Instance.SetProgressStatus(TaskbarProgressBarStatus.NoProgress);
                    break;

                case ProgressEventType.Finished:
                    if (_task.ErrorMap.Count > 0)
                    {
                        string message = Translator.Translate($"TXT_ERRORS_{_task.UpperCaseTaskType}_TASK");

                        new FileTaskErrorReport(_task.ErrorMap,
                                                Translator.Translate("TXT_ERRORS_ENCOUNTERED"), message).ShowDialog();

                        TaskbarThumbnailManager.Instance.SetProgressStatus(TaskbarProgressBarStatus.Error);
                    }
                    Close();
                    TaskbarThumbnailManager.Instance.SetProgressStatus(TaskbarProgressBarStatus.NoProgress);
                    break;

                case ProgressEventType.KeepAlive:
                case ProgressEventType.Progress:
                    txtCurFile.Text = file;
                    UpdateProgress(data);
                    break;
                }
            });
        }
        public static void OnSettingsChanged(ChangeType changeType, string persistenceId, string persistenceContext, string objectContent)
        {
            if (changeType != ChangeType.Saved)
            {
                return;
            }

            if (DetectSettingsChanges)
            {
                lock (_settingsChangesLock)
                {
                    try
                    {
                        switch (persistenceId)
                        {
                        case "LanguageID":
                        {
                            string langId = objectContent;
                            if (langId != _languageId)
                            {
                                _languageId = langId;
                                MainThread.Post((c) => Translator.SetInterfaceLanguage(_languageId));
                            }
                        }
                        break;

                        case "SkinType":
                        {
                            string skinType = objectContent;
                            if (skinType != _skinType)
                            {
                                _skinType = skinType;
                                MainThread.Post((c) => EventDispatch.DispatchEvent(EventNames.ThemeUpdated));
                            }
                        }
                        break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException(ex);
                    }
                }
            }
        }
Exemple #25
0
        protected virtual void OnAgentConnected()
        {
            ClientSession.Agent.Api.EvaluationContextManager.Events.Subscribe(
                new Observer <ICodeCellEvent> (HandleCodeCellEvent));

            void HandleCodeCellEvent(ICodeCellEvent evnt)
            {
                if (evnt is CapturedOutputSegment segment)
                {
                    MainThread.Post(() => RenderCapturedOutputSegment(segment));
                }

                if (evnt is Evaluation result)
                {
                    MainThread.Post(() => RenderResult(result));
                }
            }
        }
        public async Task StartDownloadAsync()
        {
            CancelDownload();

            cancellationTokenSource = new CancellationTokenSource();

            IsProgressBarVisible         = true;
            IsRemindMeLaterButtonVisible = false;
            IsDownloadButtonVisible      = false;
            IsCancelButtonVisible        = true;

            try {
                Telemetry.Events.UpdateEvent.Downloading(UpdateItem).Post();
                await DownloadItem.DownloadAsync(cancellationTokenSource.Token);
            } catch (Exception e) when(e is TaskCanceledException || e is OperationCanceledException)
            {
                Telemetry.Events.UpdateEvent.Canceled(UpdateItem).Post();
                return;
            } catch (Exception e) {
                var message = e.Message;
                if (e is DamagedDownloadException)
                {
                    message = Catalog.GetString("The downloaded update failed to verify.");
                }

                Log.Error(TAG, $"error downloading {DownloadItem.ActualSourceUri}", e);
                Reset();
                MainThread.Post(() => RunErrorDialog(true, message));
                Telemetry.Events.UpdateEvent.Failed(UpdateItem).Post();
                return;
            } finally {
                Log.Info(TAG, $"download operation lasted {DownloadItem.ElapsedTime}");
                Reset();
            }

            Telemetry.Events.UpdateEvent.Installing(UpdateItem).Post();

            try {
                await InstallUpdateAsync();
            } catch (Exception e) {
                Log.Error(TAG, $"error installing {DownloadItem.TargetFile}", e);
                MainThread.Post(() => RunErrorDialog(false, e.Message));
            }
        }
Exemple #27
0
        protected void CloseWaitDialog()
        {
            //if (InvokeRequired)
            //{
            //    Invoke(new MethodInvoker(CloseWaitDialog));
            //    return;
            //}

            MainThread.Post((d) =>
            {
                this.Enabled = true;

                if (_waitDialog != null)
                {
                    _waitDialog.Close();
                    _waitDialog = null;
                }
            });
        }
        private void OnFriendRemove(FriendListUpdateDto update)
        {
            Friend friend;

            if (_friends.TryRemove(update.ItemId, out friend))
            {
                var action = FriendRemoved;
                if (action != null)
                {
                    MainThread.Post(() =>
                    {
                        action(update.Data);
                    });
                }
            }
            else
            {
                _logger.Log(Diagnostics.LogLevel.Warn, "friends.remove", "Unknown friend with id " + update.ItemId);
            }
        }
Exemple #29
0
 void PostEvent(IObserver <ClientSessionEvent> observer, ClientSessionEventKind eventKind)
 => MainThread.Post(() => observer.OnNext(new ClientSessionEvent(this, eventKind)));
Exemple #30
0
        void ScheduleCheckForUpdatesPeriodicallyInBackground()
        {
            MainThread.Ensure();

            // timer callbacks may still be invoked after the timer is
            // disposed, so track a generation to know if we should
            // bail early if that circumstance arises.
            checkTimerGeneration++;
            checkTimer?.Dispose();

            TimeSpan frequency;

            switch (Prefs.Updater.QueryFrequency.GetValue())
            {
            case QueryFrequency.Never:
                Log.Debug(TAG, "Skipping check (automatic update checking disabled)");
                return;

            case QueryFrequency.Hourly:
                frequency = TimeSpan.FromHours(1);
                break;

            case QueryFrequency.Daily:
                frequency = TimeSpan.FromDays(1);
                break;

            case QueryFrequency.Weekly:
                frequency = TimeSpan.FromDays(7);
                break;

            case QueryFrequency.Startup:
            default:
                if (updateChecksPerformed == 0)
                {
                    Log.Debug(TAG, "Performing single automatic startup update check");
                    CheckForUpdatesInBackground(false, periodicUpdateHandler);
                }

                Log.Debug(TAG, "Skipping check (already performed single automatic startup check)");
                return;
            }

            var lastCheck = Prefs.Updater.LastQuery.GetValue();
            var nextCheck = frequency - (DateTime.UtcNow - lastCheck);

            if (nextCheck < TimeSpan.Zero)
            {
                nextCheck = TimeSpan.Zero;
            }

            Log.Debug(TAG, $"Scheduling check. Last check @ {lastCheck}; next in {nextCheck}");

            checkTimer = new Timer(state => MainThread.Post(() => {
                Log.Debug(TAG, "Update check timer expired");

                if ((int)state != checkTimerGeneration)
                {
                    Log.Debug(TAG, "Ignoring update check timer callback from previous generation");
                    return;
                }

                switch (Prefs.Updater.QueryFrequency.GetValue())
                {
                case QueryFrequency.Never:
                    checkTimer?.Dispose();
                    return;

                case QueryFrequency.Startup:
                    if (updateChecksPerformed > 0)
                    {
                        checkTimer?.Dispose();
                        return;
                    }
                    break;
                }

                CheckForUpdatesInBackground(false, periodicUpdateHandler);
            }), checkTimerGeneration, nextCheck, frequency);
        }